javascript
学习Spring Boot:(七)集成Mybatis
前面都是用的是spring data JPA,現(xiàn)在學(xué)習(xí)下Mybatis,而且現(xiàn)在Mybatis也像JPA那樣支持注解形式了,也非常方便,學(xué)習(xí)一下。
- 數(shù)據(jù)庫 mysql 5.7
添加依賴
在pom文件中添加:
<mybatis.version>1.3.1</mybatis.version> <druid.version>1.1.3</druid.version><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>${mybatis.version}</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>${druid.version}</version></dependency>由于springboot 默認(rèn)使用的 tomcat-jdbc數(shù)據(jù)源,為了方便,我添加了阿里巴巴的數(shù)據(jù)源。
首先了解下mybatis-spring-boot-starter 會做哪些事情:
* 自動檢測現(xiàn)有的DataSource
* 將創(chuàng)建并注冊SqlSessionFactory的實例,該實例使用SqlSessionFactoryBean將該DataSource作為輸入進行傳遞
* 將創(chuàng)建并注冊從SqlSessionFactory中獲取的SqlSessionTemplate的實例。
* 自動掃描您的mappers,將它們鏈接到SqlSessionTemplate并將其注冊到Spring上下文,以便將它們注入到您的bean中。
只要使用這個springboot mybatis starter 只需要DataSource的配置就可以使用了,它會自動創(chuàng)建使用該DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。會自動掃描你的Mappers,連接到SqlSessionTemplate,并注冊到Spring上下文中。
配置數(shù)據(jù)源
在resources/applicaiton.yml文件中添加一些數(shù)據(jù)源的連接參數(shù)配置(可選):
spring:datasource:type: com.alibaba.druid.pool.DruidDataSourcedriverClassName: com.mysql.jdbc.Driverdruid:url: jdbc:mysql://localhost:3306/learnboot?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8username: rootpassword: 123456initial-size: 10max-active: 100min-idle: 10max-wait: 60000pool-prepared-statements: truemax-pool-prepared-statement-per-connection-size: 20time-between-eviction-runs-millis: 60000min-evictable-idle-time-millis: 300000validation-query: SELECT 1test-while-idle: truetest-on-borrow: falsetest-on-return: falsestat-view-servlet:enabled: trueurl-pattern: /druid/*filter:stat:log-slow-sql: trueslow-sql-millis: 1000merge-sql: truewall:config:multi-statement-allow: truespringboot會自動加載spring.datasource.*相關(guān)配置,數(shù)據(jù)源就會自動注入到sqlSessionFactory中,sqlSessionFactory會自動注入到Mapper中,
使用Mybatis
首先我有一個SysUser,
public class SysUserEntity implements Serializable {private static final long serialVersionUID = 1L;//主鍵private Long id;//用戶名@NotBlank(message = "用戶名不能為空", groups = {AddGroup.class, UpdateGroup.class})private String username;//密碼private String password;使用XMl形式
我們來創(chuàng)建User的映射SysUserDao,也可以命名Mapper作為尾綴,這里我們寫個新增一條數(shù)據(jù)的接口,需要注意的是每個Mapper類上要加上@Mapper注解:
@Mapper public interface SysUserDao {void save(SysUserEntity user);/*** 根據(jù)條件查詢User* @param user User* @return 符合條件列表*/List<SysUserEntity> query(SysUserEntity user); }使用xml的時候需要注意的是Mybatis掃描mapper.xml并且裝配,需要在系統(tǒng)的配置文件resources/applicaiton.yml加入:
# Mybatis配置 mybatis:mapperLocations: classpath:mapper/**/*.xmlconfiguration:map-underscore-to-camel-case: true根據(jù)自己的xml目錄,進行配置。
例如:我在resources/mapper/sys目錄下面加入SysUserDao.xml文件,添加我們查詢的SQL:
使用注解形式
這個就要方便很多,沒有Mapper.xml文件了,也不要配置它的文件路徑的映射了,只要把xml中的SQL 寫到注解上就可以了。
直接在SysUserDao中改成:
根據(jù)對數(shù)據(jù)庫的操作不同,使用不同的注解:
* @Select 是查詢類的注解,所有的查詢均使用這個
* @Result 修飾返回的結(jié)果集,關(guān)聯(lián)實體類屬性和數(shù)據(jù)庫字段一一對應(yīng),如果實體類屬性和數(shù)據(jù)庫屬性名保持一致,就不需要這個屬性來修飾。
* @Insert 插入數(shù)據(jù)庫使用,直接傳入實體類會自動解析屬性到對應(yīng)的值
* @Update 負(fù)責(zé)修改,也可以直接傳入對象
* @Delete 負(fù)責(zé)刪除
注意,使用#符號和$符號的不同:
// 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);單元測試
@SpringBootTest @RunWith(SpringJUnit4ClassRunner.class) public class UserDaoTest {@Resourceprivate SysUserDao userDao;@Test@Transactional@Rollback(false)public void testSave() {SysUserEntity user = new SysUserEntity();user.setUsername("wuwii");user.setPassword("123");userDao.save(user);Assert.assertEquals(user.getUsername(), userDao.query(user).get(0).getUsername());} }總結(jié)
以上是生活随笔為你收集整理的学习Spring Boot:(七)集成Mybatis的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IoT -- (九) IoT通讯技术选型
- 下一篇: Spring Boot 之spring.