Spring Boot + MyBatis + MySQL 整合

一、前言

昨天在弄 Spring Boot 與 MyBatis 的整合,首先在網(wǎng)上查看了很多人寫的文章,參照前人的經(jīng)驗就開始整了,結(jié)果整了一天都是 bug,后來自己到官網(wǎng)上查看官方文檔后才得以順手解決,這也讓自己以后要吸取教訓(xùn),最好先看官方文檔,然后再實踐。結(jié)合自己查看的網(wǎng)上關(guān)于 Spring Boot 與 MyBatis 整合的文章,有得寫的相當復(fù)雜,有的是按照文中描述進行實踐后發(fā)現(xiàn)不行,所以自己再對其進行總結(jié)。我使用的是采用 全注解的方式來實現(xiàn) MyBatis,這也正好符合 Spring Boot 的思想:使用注解,少用配置文件。最后也加上了個使用 XML 配置的代碼。

二、整合步驟

1. 在 pom.xml 的文件中添加以下依賴:

        <!-- 添加 MyBatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.2.0</version>
        </dependency>

        <!-- 添加 MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
        </dependency>

這里我們看到在項目中使用的是 MyBatis 官方提供的 starter,mybatis-spring-boot-starter 的 Github 源碼地址為: https://github.com/mybatis/spring-boot-starter ,mybatis-spring-boot-stater的官方文檔地址:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/ ,MyBatis 官方中文文檔:http://www.mybatis.org/mybatis-3/zh/java-api.html

2. 在 application.properties 文件中添加數(shù)據(jù)庫的配置

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

3. 新建 DAO 接口,里面編寫增、刪、改、查方法

@Mapper
public interface PersonMapper {

    /**
     * 添加操作,返回新增元素的 ID
     *
     * @param personDO
     */
    @Insert("insert into person(name,age) values(#{name},#{age})")
    @Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
    void insert(PersonDO personDO);

    /**
     * 更新操作
     *
     * @param personDO
     * @return 受影響的行數(shù)
     */
    @Update("update person set name=#{name},age=#{age} where id=#{id}")
    Long update(PersonDO personDO);

    /**
     * 刪除操作
     *
     * @param id
     * @return 受影響的行數(shù)
     */
    @Delete("delete from person where id=#{id}")
    Long delete(@Param("id") Long id);

    /**
     * 查詢所有
     *
     * @return
     */
    @Select("select id,name,age from person")
    List<PersonDO> selectAll();

    /**
     * 根據(jù)主鍵查詢單個
     *
     * @param id
     * @return
     */
    @Select("select id,name,age from person where id=#{id}")
    PersonDO selectById(@Param("id") Long id);
}

這里全部使用的是注解的方式,關(guān)于 MyBatis 的所有注解,可以參考 MyBatis 的中文文檔。

4. 編寫 Controller

@EnableTransactionManagement  // 需要事務(wù)的時候加上
@RestController
public class PersonController {

    @Autowired
    private PersonMapper personMapper;

    @RequestMapping("/save")
    public Integer save() {
        PersonDO personDO = new PersonDO();
        personDO.setName("張三");
        personDO.setAge(18);
        personMapper.insert(personDO);
        return personDO.getId();
    }

    @RequestMapping("/update")
    public Long update() {
        PersonDO personDO = new PersonDO();
        personDO.setId(2);
        personDO.setName("旺旺");
        personDO.setAge(12);
        return personMapper.update(personDO);
    }

    @RequestMapping("/delete")
    public Long delete() {
        return personMapper.delete(11L);
    }

    @RequestMapping("/selectById")
    public PersonDO selectById() {
        return personMapper.selectById(2L);
    }

    @RequestMapping("/selectAll")
    public List<PersonDO> selectAll() {
        return personMapper.selectAll();
    }

    @RequestMapping("/transaction")
    @Transactional  // 需要事務(wù)的時候加上
    public Boolean transaction() {
        delete();

        int i = 3 / 0;

        save();

        return true;
    }

}

至此,運行就可以測試了,是不是很簡單。關(guān)于注解的使用可以參考這篇文章:http://blog.csdn.net/luanlouis/article/details/35780175 ,最后奉上代碼地址:https://github.com/435242634/Spring-Boot-Demo/tree/feature/3-spring-boot-mybatis

三、使用 XML 配置

上面介紹的是全使用注解的方式配置,但是很多時候我們還是使用 XML 配置 SQL 文件,這里不再多介紹,直接加上我寫的一個使用 XML 配置的代碼地址:https://github.com/435242634/Spring-Boot-Demo/tree/feature/4-spring-boot-mybatis-xml 。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容