课程表

Spring Boot课程

工具箱
速查手册

Boot 使用Mybatis

当前位置:免费教程 » Java相关 » Spring Boot
注意:本页面内容为W3xue原创,未经授权禁止转载,违者必究!
来源:W3xue  发布时间:2020/11/10 16:45:53

虽然站长很喜欢JPA的方式连接和使用数据库,但无奈国内使用Mybatis的比较多。

Orm 框架的本质是简化编程中操作数据库的编码,发展到现在基本上就剩两家了,一个是宣称可以不用写一句 Sql 的 Hibernate,一个是可以灵活调试动态 Sql 的 Mybatis ,两者各有特点,在企业级系统开发中可以根据需求灵活使用。发现一个有趣的现象:传统企业大都喜欢使用 Hibernate ,互联网行业通常使用 Mybatis 。

Hibernate 特点就是所有的 Sql 都用 Java 代码来生成,不用跳出程序去写(看) Sql ,有着编程的完整性,发展到最顶端就是 Spring Data Jpa 这种模式了,基本上根据方法名就可以生成对应的 Sql 了。具体实践请参照之前的章节Spring Boot 使用JPA连接数据库

Mybatis 初期使用比较麻烦,需要各种配置文件、实体类、Dao 层映射关联、还有一大推其它配置。当然 Mybatis 也发现了这种弊端,初期开发了generator可以根据表结果自动生产实体类、配置文件和 Dao 层代码,可以减轻一部分开发量;后期也进行了大量的优化可以使用注解了,自动管理 Dao 层和配置文件等,发展到最顶端就是今天要讲的这种模式了,mybatis-spring-boot-starter 就是 Spring Boot+ Mybatis 可以完全注解不用配置文件,也可以简单配置轻松上手。这就是 Spring Boot 的优秀之处,任何东西只要关联到 Spring Boot 都是几句注解和依赖就搞定了。


一、写配置文件,自动引入依赖包

我们在Spring Boot中使用Mybatis需要引用“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 文件,这里我们引用发布于2020年3月10日的 2.1.2版本。

在pom.xml配置文件中,增加如下依赖配置,IDE将自动下载依赖包:

  1. <dependency>
  2.     <groupId>org.mybatis.spring.boot</groupId>
  3.     <artifactId>mybatis-spring-boot-starter</artifactId>
  4.     <version>2.1.2</version>
  5. </dependency>

接下来分别简要介绍下两种开发模式。第一种是无配置文件注解模式,这个版本模式的说,就是用注解搞定一切,不需要xml配置文件。第二种是用xml配置文件注解方式,这种模式保持映射文件的老传统,接口层只需要定义空方法。在这里,本站推荐和使用第二种模式,即XML配置文件的模式。


二、两种开发模式之XML配置文件版

极简xml配置文件模式保持映射文件的老传统,接口层只需要定义空方法,系统会自动根据方法名在映射文件中找对应的 Sql。

1、配置

application.yml中新增以下配置:

  1. mybatis:
  2.   config-location: classpath:mybatis/mybatis-config.xml
  3.   mapper-locations: classpath:mybatis/mapper/*.xml

如果是application.properties,相应的新增以下配置:

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

在resources文件夹下建一个跟static和templates平行的文件夹 “mybatis”,然后新建一个配置文件“mybatis-config.xml”,内容如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  3.         "http://mybatis.org/dtd/mybatis-3-config.dtd">
  4. <configuration>
  5.  
  6.     <settings>
  7.         <setting name="mapUnderscoreToCamelCase" value="true"/>
  8.     </settings>
  9.     <typeAliases>
  10.         <typeAlias alias="Integer" type="java.lang.Integer" />
  11.         <typeAlias alias="Long" type="java.lang.Long" />
  12.         <typeAlias alias="HashMap" type="java.util.HashMap" />
  13.         <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
  14.         <typeAlias alias="ArrayList" type="java.util.ArrayList" />
  15.         <typeAlias alias="LinkedList" type="java.util.LinkedList" />
  16.  
  17.         <typeAlias type="com.w3xue.jiaocheng.bean.MainBean" alias="MainBean"/>
  18.     </typeAliases>
  19.  
  20.  
  21. </configuration>

你可以看到,除了配置了一些基础类,还配置了我们教程程序到目前为止、唯一的主类MainBean

2、添加SQL配置文件

在刚才的mybatis”文件夹中,再建立一个“mapper”文件夹,注意这里和主程序的“mapper”文件夹是不一样的。其实我们刚才已经在配置文件里配置了,因为我们设置的是“*.xml”,所以我们可以任意设置自己命名的XML文件。这里我们建好文件夹后,在“mapper”文件夹新建一个“MainMapper.xml”文件,内容如下:

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  3.  
  4. <mapper namespace="com.w3xue.jiaocheng.mapper.MybatisDao">
  5.  
  6.     <resultMap id="BaseResultMap" type="com.w3xue.jiaocheng.bean.MainBean" >
  7.         <result column="f_id" property="id" jdbcType="INTEGER" />
  8.         <result column="f_name" property="name" jdbcType="VARCHAR" />
  9.         <result column="f_age" property="age" jdbcType="BIGINT" />
  10.         <result column="f_grade" property="grade" jdbcType="INTEGER" />
  11.         <result column="f_class" property="studentClass" jdbcType="VARCHAR" />
  12.         <result column="f_parent_name" property="parent_name" jdbcType="VARCHAR" />
  13.         <result column="f_parent_mobilephone" property="parent_mobilephone" jdbcType="VARCHAR" />
  14.     </resultMap>
  15.  
  16.     <sql id="Base_Column_List">f_id, f_name, f_age, f_grade, f_class, f_parent_name,f_parent_mobilephone</sql>
  17.  
  18.     <select id="listStudents" resultMap="BaseResultMap">
  19.         SELECT * FROM t_w3xue_student
  20.     </select>
  21.  
  22.     <select id="findStudentById" parameterType="java.lang.Integer" resultMap="BaseResultMap">
  23.         SELECT * FROM t_w3xue_student WHERE f_id = #{id}
  24.     </select>
  25.  
  26.     <insert id="addStudent" parameterType="MainBean" useGeneratedKeys="true" keyProperty="id">
  27.         INSERT INTO t_w3xue_student(f_id, f_name,  f_age, f_grade, f_class , f_parent_name , f_parent_mobilephone)
  28.         VALUES (#{id}, #{name}, #{age} ,#{grade},#{studentClass},#{parent_name},#{parent_mobilephone})
  29.     </insert>
  30.  
  31.     <update id="addAge" parameterType="int">
  32.         update t_w3xue_student <set> f_age = f_age+1 </set> where f_id = #{id}
  33.     </update>
  34.  
  35.     <update id="updateInfo" parameterType="MainBean">
  36.         UPDATE t_w3xue_student SET
  37.         <if test="name != null">f_name = #{name},</if>
  38.         <if test="age != null">f_age = #{age},</if>
  39.         <if test="grade != null">f_grade = #{grade},</if>
  40.         <if test="studentClass != null">f_class = #{studentClass},</if>
  41.         <if test="parent_name != null">f_parent_name = #{parent_name},</if>
  42.         <if test="parent_mobilephone != null">f_parent_mobilephone = #{parent_mobilephone},</if>
  43.         f_id = #{id}
  44.         WHERE
  45.         f_id = #{id}
  46.     </update>
  47.  
  48.     <delete id="delete" parameterType="java.lang.Integer" >
  49.         DELETE FROM
  50.         t_w3xue_student
  51.         WHERE
  52.         f_id =#{id}
  53.     </delete>
  54. </mapper>

3、编写 Mapper 层的代码

在程序目录“mapper”文件夹下,添加一个MybatisDao接口,然后只需要定义刚才在“MainMapper.xml”文件里定义的接口方法

  1. package com.w3xue.jiaocheng.mapper;
  2.  
  3. import com.w3xue.jiaocheng.bean.MainBean;
  4. import org.apache.ibatis.annotations.Mapper;
  5. import org.springframework.stereotype.Repository;
  6.  
  7. import java.util.List;
  8.  
  9. @Repository
  10. //@Mapper
  11. public interface MybatisDao {
  12.  
  13.     List<MainBean> listStudents();
  14.  
  15.     MainBean findStudentById(int id);
  16.  
  17.     void addStudent(MainBean mb);
  18.  
  19.     void addAge(Integer id);
  20.  
  21.     void updateInfo(MainBean mb);
  22.  
  23.     void delete(int id);
  24.  
  25. }

这里,我们看到一个被注释的@Mapper注解,这里,一般情况下是需要这个注解的,没有就会出现错误。但是,如果项目复杂,不止一个Dao层的接口,那么,每个都注解就很麻烦。我们在主程序JiaochengApplication类上加上这样一个注解,Spring Boot就会自动在这个文件夹里寻找Dao层的接口(即mapper类):

  1. @MapperScan("com.w3xue.jiaocheng.mapper")
  2. @SpringBootApplication
  3. public class JiaochengApplication extends SpringBootServletInitializer {
  4.     ....
  5. }

这个注解和主程序的“@SpringBootApplication”注解平行。

4、使用和测试

最后,我们把这些定义的方法拿进Controller层里面使用,看一下效果。鉴于MainRestController类已经有些超载,我们这里在controller文件夹中,新建一个Controller类MybatisController,完整代码如下:

  1. package com.w3xue.jiaocheng.controller;
  2.  
  3. import com.w3xue.jiaocheng.bean.MainBean;
  4. import com.w3xue.jiaocheng.mapper.MainDao;
  5. import com.w3xue.jiaocheng.mapper.MybatisDao;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RequestMethod;
  9. import org.springframework.web.bind.annotation.RequestParam;
  10. import org.springframework.web.bind.annotation.RestController;
  11. import java.util.List;
  12.  
  13. @RestController
  14. public class MybatisController {
  15.  
  16.     @Autowired
  17.     private MybatisDao mybatisDao;
  18.     @Autowired
  19.     private MainDao mainDao;
  20.  
  21.     //选取单个学生
  22.     @RequestMapping(value="/getone",method= RequestMethod.GET)
  23.     public String getone() {
  24.         StringBuilder sb=new StringBuilder();
  25.         MainBean mb= mybatisDao.findStudentById(2); //取得单个学生信息
  26.         sb.append(mb.getName());
  27.         return sb.toString();
  28.     }
  29.  
  30.     //选取多个学生
  31.     @RequestMapping(value="/getmutiple",method= RequestMethod.GET)
  32.     public String getmutiple() {
  33.         StringBuilder sb=new StringBuilder();
  34.         List<MainBean> mbs= mybatisDao.listStudents(); //取得所有学生信息
  35.         for (MainBean mb:mbs) {
  36.             sb.append(mb.getName()+"<br />");
  37.         }
  38.         return sb.toString();
  39.     }
  40.  
  41.     //添加学生信息
  42.     @RequestMapping(value="/addstudent",method= RequestMethod.GET)
  43.     public String addstudent() {
  44.         MainBean mb=new MainBean();
  45.         mb.setName("赵六");
  46.         mb.setAge(10);
  47.         mb.setGrade("三年级");
  48.         mb.setStudentClass("三班");
  49.         mb.setParent_name("赵钱孙");
  50.         mb.setParent_mobilephone("19988882222");
  51.         try {
  52.             mybatisDao.addStudent(mb);
  53.             return "保存成功";
  54.         }catch (Exception e) {
  55.             return "保存失败";
  56.         }
  57.  
  58.     }
  59.  
  60.     //修改单个字段信息
  61.     @RequestMapping(value="/addage",method= RequestMethod.GET)
  62.     public String addage() {
  63.         StringBuilder sb=new StringBuilder();
  64.         MainBean mb= mybatisDao.findStudentById(4);  //取得编号为4的学生信息
  65.         sb.append("修改之前"+mb.getName()+"的年龄:"+mb.getAge());
  66.         mybatisDao.addAge(4);  //给编号为4的学生加年龄
  67.         MainBean mb2= mybatisDao.findStudentById(4); //再次取得编号为4的学生信息
  68.         sb.append("<br />修改之后"+mb2.getName()+"的年龄:"+mb2.getAge());
  69.         return sb.toString();
  70.     }
  71.  
  72.     //更新单个学生信息
  73.     @RequestMapping(value="/updateInfo",method= RequestMethod.GET)
  74.     public String updateInfo() {
  75.         StringBuilder sb=new StringBuilder();
  76.         MainBean mb= mybatisDao.findStudentById(4);  //取得编号为4的学生信息
  77.         sb.append("【修改之前】姓名:"+mb.getName()+",年龄:"+mb.getAge()+",年级:"+mb.getGrade()+",班级:"+mb.getStudentClass()+",父母姓名:"+mb.getParent_name()+",父母电话:"+mb.getParent_mobilephone());
  78.         mb.setAge(11);
  79.         mb.setGrade("四年级");
  80.         mb.setParent_mobilephone("12266667777");
  81.         mybatisDao.updateInfo(mb);
  82.         MainBean mb2= mybatisDao.findStudentById(4); //再次取得编号为4的学生信息
  83.         sb.append("<br />【修改之后】姓名:"+mb2.getName()+",年龄:"+mb2.getAge()+",年级:"+mb2.getGrade()+",班级:"+mb2.getStudentClass()+",父母姓名:"+mb2.getParent_name()+",父母电话:"+mb2.getParent_mobilephone());
  84.         return sb.toString();
  85.     }
  86.  
  87.  
  88.     //删除单个学生信息
  89.     @RequestMapping(value="/mybatisdel",method= RequestMethod.GET)
  90.     public String mybatisdel(@RequestParam(value = "id",defaultValue = "") Integer pId) {
  91.         try {
  92.             mybatisDao.delete(pId);
  93.             return "删除ID为" + pId + "的学生成功";
  94.         }
  95.         catch (Exception e)
  96.         {
  97.             return "删除失败";
  98.         }
  99.     }
  100.     
  101. }

这里的代码都十分简单,这里就不再赘述了,注意下,有的方法是有参数的,访问的时候,加上相关参数就可以了。

这里直接使用了MybatisDao接口里面的所有方法,涵盖了数据的增删改查。经过适当的变动,基本就可以满足对于数据库的日常改动了。

注意:本页面内容为W3xue原创,未经授权禁止转载,违者必究!
来源:W3xue  发布时间:2020/11/10 16:45:53
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号