MyBatis 是一款優秀的持久層框架,它支持定製化 SQL、存儲過程以及高級映射。MyBatis 避免了幾乎全部的 JDBC 代碼和手動設置參數以及獲取結果集。MyBatis 可使用簡單的 XML 或註解來配置和映射原生信息,將接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java對象)映射成數據庫中的記錄。 本文將簡單的演示在Spring Boot使用Mybatis的兩種方式:使用註解的方式、使用XML配置的方式。 **1、使用註解方式使用Mybatis** 所謂無配置註解指的是不使用xml配置,全部和Mybatis相關的映射都使用註解來完成(包括Mapper掃描、查詢結果與entity的映射等)。 **1.1 在pom.xml文件中添加必要依賴以下** ``` org.mybatis.spring.boot mybatis-spring-boot-starter 1.3.1 org.springframework.boot< spring-boot-starter-web org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-starter-web mysql mysql-connector-java runtime org.springframework.boot spring-boot-starter-test test ``` 在所添加的依賴中,咱們簡單解說一下mybatis-spring-boot-starter,mybatis-spring-boot-starter能夠幫助你在Spring Boot中快速構建Mybatis應用,在Spring Boot中使用此starter有以下好處: - 減小代碼模板(幾乎不須要); - 減小XML配置; - 自動檢測存在的DataSource; - 自動使用SqlSessionFactoryBean傳遞DataSource做爲一個輸入建立和註冊一個SqlSessionFactory實例; - 自動使用SqlSessionFactory建立和註冊一個SqlSessionTemplate實例; - 自動掃描mapper,鏈接這些mapper和SqlSessionTemplate並註冊mapper到spring上下文,這樣一來這些mapper就能夠被注入爲您的bean。 **1.2 application.properties配置** ``` mybatis.type-aliases-package=com.learnspringboot.mybatis.entity spring.datasource.url=jdbc:mysql://127.0.0.1:3306/ron_intelligence_system?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=true&allowMultiQueries=true&serverTimezone=Asia/Hong_Kong spring.datasource.username=root spring.datasource.password=111111 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.tomcat.max-wait=10000 spring.datasource.tomcat.max-active=50 spring.datasource.tomcat.test-on-borrow=true spring.datasource.testWhileIdle=true spring.datasource.timeBetweenEvictionRunsMillis=60001 ``` springboot會自動加載spring.datasource.*相關配置,數據源就會自動注入到sqlSessionFactory中,sqlSessionFactory會自動注入到Mapper中,然而這些過程你都不用管,這些都是自動完成的,直接拿起來使用就好了。 在啓動類中添加對mapper包掃描@MapperScan ``` @SpringBootApplication @MapperScan("com.learnspringboot.mybatis.mapper") public class MybatisApplication { public static void main(String[] args) { SpringApplication.run(MybatisApplication.class, args); } } ``` 或者直接在Mapper類上面添加註解
@Mapper,建議使用上面那種,否則每一個mapper加個註解也挺麻煩的。 **1.3 開發Mapper** ``` public interface BlogTypeMapper { @Select("select * from blog_type") @Results({ @Result(property = "id",column = "id"), @Result(property = "btId",column = "bt_id"), @Result(property = "typeTxt",column = "type_txt"), @Result(property = "userId",column = "user_id"), @Result(property = "crtTime",column = "crt_time") }) List getAll(); @Select("select * from blog_type where bt_id=#{btId}") @Results({ @Result(property = "id",column = "id"), @Result(property = "btId",column = "bt_id"), @Result(property = "typeTxt",column = "type_txt"), @Result(property = "userId",column = "user_id"), @Result(property = "crtTime",column = "crt_time") }) BlogType getOne(String btId); @Insert("insert into blog_type(bt_id,type_txt,user_id,crt_time) values(#{btId},#{typeTxt},#{userId},#{crtTime})") void insert(BlogType type); @Update("update blog_type set type_txt=#{typeTxt},user_id=#{userId},crt_time=#{crtTime} where bt_id=#{btId}") void update(BlogType type); @Delete("delete from blog_type where bt_id=#{btId}") void delete(String btId); } ``` - @Select 是查詢類的註解,全部的查詢均使用這個 - @Result 修飾返回的結果集,關聯實體類屬性和數據庫字段一一對應,若是實體類屬性和數據庫屬性名保持一致,就不須要這個屬性來修飾。 - @Insert 插入數據庫使用,直接傳入實體類會自動解析屬性到對應的值 - @Update 負責修改,也能夠直接傳入對象 - @Delete 負責刪除 **1.4 使用** 第三步基本上完成了Dao的開發,在須要使用的地方使用@Autowired註解基本就可以使用,咱們使用單元測試進行測試。 ``` @RunWith(SpringRunner.class) @SpringBootTest public class MybatisApplicationTests { @Autowired private BlogTypeMapper blogTypeMapper; @Test public void testInsert() { System.out.println("----------測試插入------"); BlogType type=new BlogType(); type.setBtId("455550e8ba444f8aabdd696a0976a6bc"); type.setTypeTxt("Spring Boot MyBatis 實例講解"); type.setUserId("80bda1819d4a4619b44750bfc3013183"); type.setCrtTime(new Date()); blogTypeMapper.insert(type); type.setBtId("455550e8ba444f8aabdd696a0976a6ba"); type.setTypeTxt("Spring Boot系列"); blogTypeMapper.insert(type); type.setBtId("455550e8ba444f8aabdd696a0976a6bb"); type.setTypeTxt("Spring Boot系列哈哈哈"); blogTypeMapper.insert(type); testQuery(); } @Test public void testUpdate(){ System.out.println("----------測試更新------"); BlogType type=blogTypeMapper.getOne("455550e8ba444f8aabdd696a0976a6bb"); type.setTypeTxt("學習Spring Boot Mybatis"); blogTypeMapper.update(type); type = blogTypeMapper.getOne("455550e8ba444f8aabdd696a0976a6bb"); System.out.println(type.getBtId()+"------>"+type.getTypeTxt()); } @Test public void testQuery(){ List list=blogTypeMapper.getAll(); System.out.println("----------查詢數據------"); list.stream().forEach(item->{ System.out.println(item.getBtId()+"------>"+item.getTypeTxt()); }); } @Test public void testDelete(){ System.out.println("----------測試刪除------"); blogTypeMapper.delete("455550e8ba444f8aabdd696a0976a6bb"); testQuery(); } } ``` **2、使用XML配置的方式使用Mybatis** pom文件配置與上面所描述的一致,這裏再也不贅述。只是使用XML配置的方式,咱們須要在配置文件中增長實體類映射xml文件的配置路徑以及Mybatis基礎配置文件的路徑。在application.properties新增如下配置: ``` mybatis.config-locations=classpath:mybatis/mybatis-config.xml mybatis.mapper-locations=classpath:mybatis/mapper/*.xml ``` **2.1 mybatis-config.xml 配置(實例以最簡單的模式演示)** ``` ``` **2.2 添加BlogType映射文件** ``` id, bt_id, type_txt, user_id, crt_time select from blog_type where bt_id = #{btId} select from blog_type delete from blog_type where bt_id = #{btId} insert into blog_type (id, bt_id, type_txt, user_id, crt_time) values (#{id}, #{btId}, #{typeTxt}, #{userId}, #{crtTime}) update blog_type set type_txt = #{typeTxt}, user_id = #{userId}, crt_time = #{crtTime} where bt_id = #{btId} ``` **2.3 編寫Dao層代碼** ``` public interface BlogTypeMapper { List getAll(); BlogType getOne(String btId); void insert(BlogType type); void update(BlogType type); void delete(String btId); } ```