'Spring Boot(六):如何優雅的使用 Mybatis'

MySQL Java 碼農老蔥 2019-08-24
"

Mybatis 初期使用比較麻煩,需要各種配置文件、實體類、Dao 層映射關聯、還有一大推其它配置。當然 Mybatis 也發現了這種弊端,初期開發了generator可以根據表結果自動生產實體類、配置文件和 Dao 層代碼,可以減輕一部分開發量;後期也進行了大量的優化可以使用註解了,自動管理 Dao 層和配置文件等,發展到最頂端就是今天要講的這種模式了,mybatis-spring-boot-starter 就是 Spring Boot+ Mybatis 可以完全註解不用配置文件,也可以簡單配置輕鬆上手。

現在想想 Spring Boot 就是牛逼呀,任何東西只要關聯到 Spring Boot 都是化繁為簡。

mybatis-spring-boot-starter

官方說明:MyBatis Spring-Boot-Starter will help you use MyBatis with Spring Boot

其實就是 Mybatis 看 Spring Boot 這麼火熱也開發出一套解決方案來湊湊熱鬧,但這一湊確實解決了很多問題,使用起來確實順暢了許多。mybatis-spring-boot-starter主要有兩種解決方案,一種是使用註解解決一切問題,一種是簡化後的老傳統。

當然任何模式都需要首先引入mybatis-spring-boot-starter的 Pom 文件,現在最新版本是 2.0.0

<dependency>
\t<groupId>org.mybatis.spring.boot</groupId>
\t<artifactId>mybatis-spring-boot-starter</artifactId>
\t<version>2.0.0</version>
</dependency>

好了下來分別介紹兩種開發模式

無配置文件註解版

就是一切使用註解搞定。

1 添加相關 Maven 文件

<dependencies>
\t<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
\t<dependency>
\t\t<groupId>org.mybatis.spring.boot</groupId>
\t\t<artifactId>mybatis-spring-boot-starter</artifactId>
\t\t<version>2.0.0</version>
\t</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>

完整的 Pom 包這裡就不貼了,大家直接看源碼

2、application.properties 添加相關配置

mybatis.type-aliases-package=com.neo.model
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

Spring Boot 會自動加載 spring.datasource.* 相關配置,數據源就會自動注入到 sqlSessionFactory 中,sqlSessionFactory 會自動注入到 Mapper 中,對了,你一切都不用管了,直接拿起來使用就行了。

在啟動類中添加對 mapper 包掃描@MapperScan

@SpringBootApplication
@MapperScan("com.neo.mapper")
public class MybatisAnnotationApplication {
\tpublic static void main(String[] args) {
\t\tSpringApplication.run(MybatisAnnotationApplication.class, args);
\t}
}

或者直接在 Mapper 類上面添加註解@Mapper,建議使用上面那種,不然每個 mapper 加個註解也挺麻煩的

3、開發 Mapper

第三步是最關鍵的一塊, Sql 生產都在這裡

public interface UserMapper {
\t
\t@Select("SELECT * FROM users")
\t@Results({
\t\t@Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class),
\t\t@Result(property = "nickName", column = "nick_name")
\t})
\tList<UserEntity> getAll();
\t
\t@Select("SELECT * FROM users WHERE id = #{id}")
\t@Results({
\t\t@Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class),
\t\t@Result(property = "nickName", column = "nick_name")
\t})
\tUserEntity getOne(Long id);
\t@Insert("INSERT INTO users(userName,passWord,user_sex) VALUES(#{userName}, #{passWord}, #{userSex})")
\tvoid insert(UserEntity user);
\t@Update("UPDATE users SET userName=#{userName},nick_name=#{nickName} WHERE id =#{id}")
\tvoid update(UserEntity user);
\t@Delete("DELETE FROM users WHERE id =#{id}")
\tvoid delete(Long id);
}

為了更接近生產我特地將 user_sex、nick_name 兩個屬性在數據庫加了下劃線和實體類屬性名不一致,另外 user_sex 使用了枚舉

  • @Select 是查詢類的註解,所有的查詢均使用這個
  • @Result 修飾返回的結果集,關聯實體類屬性和數據庫字段一一對應,如果實體類屬性和數據庫屬性名保持一致,就不需要這個屬性來修飾。
  • @Insert 插入數據庫使用,直接傳入實體類會自動解析屬性到對應的值
  • @Update 負責修改,也可以直接傳入對象
  • @delete 負責刪除

瞭解更多屬性參考這裡

注意,使用#符號和$符號的不同:

// This example creates a prepared statement, something like select * from teacher where name = ?;
@Select("Select * from teacher where name = #{name}")
Teacher selectTeachForGivenName(@Param("name") String name);
// This example creates n inlined statement, something like select * from teacher where name = 'someName';
@Select("Select * from teacher where name = '${name}'")
Teacher selectTeachForGivenName(@Param("name") String name);

4、使用

上面三步就基本完成了相關 Mapper 層開發,使用的時候當作普通的類注入進入就可以了

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
\t@Autowired
\tprivate UserMapper userMapper;
\t@Test
\tpublic void testInsert() throws Exception {
\t\tuserMapper.insert(new User("aa1", "a123456", UserSexEnum.MAN));
\t\tuserMapper.insert(new User("bb1", "b123456", UserSexEnum.WOMAN));
\t\tuserMapper.insert(new User("cc1", "b123456", UserSexEnum.WOMAN));
\t\tAssert.assertEquals(3, userMapper.getAll().size());
\t}
\t@Test
\tpublic void testQuery() throws Exception {
\t\tList<User> users = userMapper.getAll();
\t\tSystem.out.println(users.toString());
\t}
\t
\t
\t@Test
\tpublic void testUpdate() throws Exception {
\t\tUser user = userMapper.getOne(30l);
\t\tSystem.out.println(user.toString());
\t\tuser.setNickName("neo");
\t\tuserMapper.update(user);
\t\tAssert.assertTrue(("neo".equals(userMapper.getOne(30l).getNickName())));
\t}
}

源碼中 Controller 層有完整的增刪改查,這裡就不貼了

極簡 xml 版本

極簡 xml 版本保持映射文件的老傳統,接口層只需要定義空方法,系統會自動根據方法名在映射文件中找對應的 Sql .

1、配置

pom 文件和上個版本一樣,只是application.properties新增以下配置

mybatis.config-location=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

指定了 Mybatis 基礎配置文件和實體類映射文件的地址

mybatis-config.xml 配置

<configuration>
\t<typeAliases>
\t\t<typeAlias alias="Integer" type="java.lang.Integer" />
\t\t<typeAlias alias="Long" type="java.lang.Long" />
\t\t<typeAlias alias="HashMap" type="java.util.HashMap" />
\t\t<typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
\t\t<typeAlias alias="ArrayList" type="java.util.ArrayList" />
\t\t<typeAlias alias="LinkedList" type="java.util.LinkedList" />
\t</typeAliases>
</configuration>

這裡也可以添加一些 Mybatis 基礎的配置

2、添加 User 的映射文件

<mapper namespace="com.neo.mapper.UserMapper" >
<resultMap id="BaseResultMap" type="com.neo.entity.UserEntity" >
<id column="id" property="id" jdbcType="BIGINT" />
<result column="userName" property="userName" jdbcType="VARCHAR" />
<result column="passWord" property="passWord" jdbcType="VARCHAR" />
<result column="user_sex" property="userSex" javaType="com.neo.enums.UserSexEnum"/>
<result column="nick_name" property="nickName" jdbcType="VARCHAR" />
</resultMap>

<sql id="Base_Column_List" >
id, userName, passWord, user_sex, nick_name
</sql>
<select id="getAll" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
\t FROM users
</select>
<select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
\t FROM users
\t WHERE id = #{id}
</select>
<insert id="insert" parameterType="com.neo.entity.UserEntity" >
INSERT INTO
\t\tusers
\t\t(userName,passWord,user_sex)
\tVALUES
\t\t(#{userName}, #{passWord}, #{userSex})
</insert>

<update id="update" parameterType="com.neo.entity.UserEntity" >
UPDATE
\t\tusers
SET
\t<if test="userName != null">userName = #{userName},</if>
\t<if test="passWord != null">passWord = #{passWord},</if>
\tnick_name = #{nickName}
WHERE
\t\tid = #{id}
</update>

<delete id="delete" parameterType="java.lang.Long" >
DELETE FROM
\t\t users
WHERE
\t\t id =#{id}
</delete>
</mapper>

其實就是把上個版本中 Mapper 的 Sql 搬到了這裡的 xml 中了

3、編寫 Mapper 層的代碼

public interface UserMapper {
\t
\tList<UserEntity> getAll();
\t
\tUserEntity getOne(Long id);
\tvoid insert(UserEntity user);
\tvoid update(UserEntity user);
\tvoid delete(Long id);
}

對比上一步,這裡只需要定義接口方法。

"

相關推薦

推薦中...