Spring Boot整合Mybatis实例

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); } ```