Spring Boot 入門示例(十二):Spring Boot 集成 MyBatis(註解方式)操作數據庫

Spring Boot 集成 MyBatis(註解方式)操作數據庫

註解方式相較於 XML 方式而言,SQL 語句查找方便,直接放在接口方法的註解上,可以很容易找到,但 SQL 語句排版效果不是很好,如果是複雜的 SQL 語句很難看明白它的邏輯,並且對動態 SQL 語句的支持很差,需要單獨提供生成 SQL 語句的方法。

下面,我們來看看基於註解方式的 MyBatis 如何配置。

添加 MyBatis 依賴

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>

配置數據源信息

  • application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/game?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

創建 Mapper 類

@Mapper // 此處可以不用添加註解,可以統一在啓動類上添加 @MapperScan
public interface UserMapper {

    @Select("SELECT * FROM user WHERE NAME = #{name}")
    Users findByName(@Param("name") String name);

    @Insert("INSERT INTO user(NAME, password) VALUES(#{name}, #{password})")
    int insert(@Param("name") String name, @Param("password") String password);

    @UpdateProvider(type = UserDAOProvider.class, method = "updateByPrimaryKey")
    int updateById(@Param("user") User user);
}

其中,Update 方法使用的是一個 type 和一個 method 屬性來指定,它們指定了 Provider 類中的一個方法。因爲在進行數據更新時需要判斷字段是否爲空來決定是否更新這個字段,而在 XML 配置中可以使用 <if> 標籤實現。如果使用註解的方式,就只能通過提供一個 Provider 類來動態生成 SQL 語句。

  • UserDAOProvider.class
public class UserDAOProvider {

    public String updateByPrimaryKey(Map<String, Object> map) {
        User user = (User) map.get("user");
        if (user == null || user.getId() == null) {
            throw new RuntimeException("The primaryKey can not be null.");
        }
        // 拼接 sql 語句
        StringBuilder updateStrSb = new StringBuilder("UPDATE user SET ");
        StringBuilder setStrSb = new StringBuilder();
        if (user.getUsername() != null) {
            setStrSb.append("username = #{user.username},");
        }
        if (user.getPassword() != null) {
            setStrSb.append("password = #{user.password}");
        }

        if (setStrSb.length() <= 0) {
            throw new RuntimeException("None element to update.");
        }
        updateStrSb.append(setStrSb).append(" WHERE id = #{user.id}");

        return updateStrSb.toString();
    }
}

在啓動類上添加 @MapperScan 註解

MyBatis 啓動時可以不在 mapper 層加上 @Mapper 註解,但是一定要在啓動類上加上 @MapperScan 註解,並指定掃包範圍。如果在 mapper 接口類上加上了 @Mapper 註解,就不需要在啓動類上加上 @MapperScan 註解了。

@SpringBootApplication
@MapperScan(basePackages = "com.example.mybatis.mapper")
public class MybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisApplication.class, args);
    }

}

這樣,MyBatis 註解方式的使用配置就完成了,接下來就可以操作數據庫啦!

最後,詳細代碼可以查看本示例的 Demo。

後記

由於自身能力有限,若有錯誤或者不當之處,還請大家批評指正,一起學習交流!

GitHub 源碼地址:springboot-mybatis-annotation

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章