SpringBoot集成mybatis配置
一個有趣的現象:傳統企業大都喜歡使用hibernate,互聯網行業通常使用mybatis;之所以出現這個問題感覺與對應的業務有關,比方說,互聯網的業務更加的復雜,更加需要進行靈活性的處理,所以mybatis的靈活性特點更為適合其
作為技術選型的優勢;
mybatis初期使用比較麻煩,需要各種配置文件、實體類、dao層映射關聯、還有一大推其它配置。當然mybatis也發現了這種弊端,初期開發了可以根據表結果自動生產實體類、配置文件和dao層代碼,可以減輕一部分開發量;后期也進行了大量的優化可以使用注解了,自動管理dao層和配置文件等,發展到最頂端就是今天要講的這種模式了。
mybatis-spring-boot-starter就是springboot+mybatis可以完全注解不用配置文件,也可以簡單配置輕松上手。
mybatis-spring-boot-starter
任何模式都需要首先引入mybatis-spring-boot-starter的pom文件。
一、極簡xml版本 【個人推薦使用這種方式,松耦合性】
極簡xml版本保持映射文件的老傳統,優化主要體現在不需要實現dao的實現層【只需要定義接口類和方法】,系統會自動根據方法名在映射文件中找對應的sql【由namespace和名稱坐標確定】。
1、配置
pom.xml文件【部分】:
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.1.1</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional></dependency>
</dependencies>
application.properties新增以下配置
mybatis.config-location=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
指定了mybatis基礎配置文件和實體類映射文件的地址
mybatis-config.xml 配置
<configuration><typeAliases><typeAlias alias="Integer" type="java.lang.Integer" /><typeAlias alias="Long" type="java.lang.Long" /><typeAlias alias="HashMap" type="java.util.HashMap" /><typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" /><typeAlias alias="ArrayList" type="java.util.ArrayList" /><typeAlias alias="LinkedList" type="java.util.LinkedList" /></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" />FROM users</select><select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" >SELECT <include refid="Base_Column_List" />FROM usersWHERE id = #{id}</select><insert id="insert" parameterType="com.neo.entity.UserEntity" >INSERT INTO users(userName,passWord,user_sex) VALUES(#{userName}, #{passWord}, #{userSex})</insert><update id="update" parameterType="com.neo.entity.UserEntity" >UPDATE users SET <if test="userName != null">userName = #{userName},</if><if test="passWord != null">passWord = #{passWord},</if>nick_name = #{nickName}WHERE id = #{id}</update><delete id="delete" parameterType="java.lang.Long" >DELETE FROMusers WHERE id =#{id}</delete>
</mapper>
其實就是把上個版本中mapper的sql搬到了這里的xml中了
3、編寫Dao層的代碼【定義接口】
public interface UserMapper {List<UserEntity> getAll();UserEntity getOne(Long id);void insert(UserEntity user);void update(UserEntity user);void delete(Long id);
}
對比上一步這里全部只剩了接口方法
二、無配置文件注解版【耦合性高】
就是一切使用注解搞定。
1 添加相關maven文件【同上】
2、application.properties 添加相關配置
mybatis.type-aliases-package=com.neo.entity
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = root
springboot會自動加載spring.datasource.*相關配置,數據源就會自動注入到sqlSessionFactory中,sqlSessionFactory會自動注入到Mapper中,對了你一切都不用管了,直接拿起來使用就行了。
在啟動類中添加對mapper包掃描@MapperScan
@SpringBootApplication
@MapperScan("com.neo.mapper")
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}
或者直接在Mapper類上面添加注解@Mapper,建議使用上面那種,不然每個mapper加個注解也挺麻煩的
3、開發Mapper
第三步是最關鍵的一塊,sql生產都在這里
public interface UserMapper {@Select("SELECT * FROM users")@Results({@Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class),@Result(property = "nickName", column = "nick_name")})List<UserEntity> getAll();@Select("SELECT * FROM users WHERE id = #{id}")@Results({@Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class),@Result(property = "nickName", column = "nick_name")})UserEntity getOne(Long id);
}
為了更接近生產我特地將user_sex、nick_name兩個屬性在數據庫加了下劃線和實體類屬性名不一致,另外user_sex使用了枚
4、使用
上面三步就基本完成了相關dao層開發,使用的時候當作普通的類注入進入就可以了
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {@Autowiredprivate UserMapper UserMapper;@Testpublic void testInsert() throws Exception {UserMapper.insert(new UserEntity("aa", "a123456", UserSexEnum.MAN));UserMapper.insert(new UserEntity("bb", "b123456", UserSexEnum.WOMAN));UserMapper.insert(new UserEntity("cc", "b123456", UserSexEnum.WOMAN));Assert.assertEquals(3, UserMapper.getAll().size());}
}