Spring Boot整合MyBatis

📅 2026/8/17 21:29:41
Spring Boot整合MyBatis
一、前言整合MyBatis之前先搭建一个基本的Spring Boot项目开启Spring Boot。然后引入mybatis-spring-boot-starter和数据库连接驱动这里使用关系型数据库mysql5.7.30。二、mybatis-spring-boot-starter在pom中引入dependencygroupIdorg.mybatis.spring.boot/groupIdartifactIdmybatis-spring-boot-starter/artifactIdversion2.1.1/version/dependency不同版本的Spring Boot和MyBatis版本对应不一样具体可查看官方文档http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/三、引入mysql在pom中引入mysql驱动dependencygroupIdmysql/groupIdartifactIdmysql-connector-java/artifactIdscoperuntime/scope/dependency四、Druid数据源Druid是一个关系型数据库连接池是阿里巴巴的一个开源项目地址https://github.com/alibaba/druid。Druid不但提供连接池的功能还提供监控功能可以实时查看数据库连接池和SQL查询的工作情况。4.1 配置Druid依赖Druid为Spring Boot项目提供了对应的starterdependencygroupIdcom.alibaba/groupIdartifactIddruid-spring-boot-starter/artifactIdversion1.1.22/version/dependency4.2 Druid数据源配置上面通过查看mybatis starter的隐性依赖发现Spring Boot的数据源配置的默认类型是org.apache.tomcat.jdbc.pool.Datasource为了使用Druid连接池需要在application.yml下配置spring: datasource: druid: # 数据库访问配置, 使用druid数据源 type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://192.168.2.117:3306/springboot?useUnicodetruecharacterEncodingutf8serverTimezoneUTCallowMultiQueriestrueuseSSLfalse username: spring password: spring#123 # 连接池配置 initial-size: 5 min-idle: 5 max-active: 20 # 连接等待超时时间 max-wait: 30000 # 配置检测可以关闭的空闲连接间隔时间 time-between-eviction-runs-millis: 60000 # 配置连接在池中的最小生存时间 min-evictable-idle-time-millis: 300000 validation-query: select 1 from dual test-while-idle: true test-on-borrow: false test-on-return: false # 打开PSCache并且指定每个连接上PSCache的大小 pool-prepared-statements: true max-open-prepared-statements: 20 max-pool-prepared-statement-per-connection-size: 20 # 配置监控统计拦截的filters, 去掉后监控界面sql无法统计, wall用于防火墙 filters: stat,wall # Spring监控AOP切入点如x.y.z.service.*,配置多个英文逗号分隔 aop-patterns: com.springboot.servie.* # WebStatFilter配置 web-stat-filter: enabled: true # 添加过滤规则 url-pattern: /* # 忽略过滤的格式 exclusions: *.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/* # StatViewServlet配置 stat-view-servlet: enabled: true # 访问路径为/druid时跳转到StatViewServlet url-pattern: /druid/* # 是否能够重置数据 reset-enable: false # 需要账号密码才能访问控制台 login-username: druid login-password: druid123 # IP白名单 # allow: 127.0.0.1 # IP黑名单共同存在时deny优先于allow # deny: 192.168.1.218 # 配置StatFilter filter: stat: log-slow-sql: true上述配置不但配置了Druid作为连接池而且还开启了Druid的监控功能。 其他配置可参考官方wiki——https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter此时运行项目访问http://localhost:8080/druid输入账号密码即可看到Druid监控后台关于Druid的更多说明可查看官方wiki——https://github.com/alibaba/druid/wiki/常见问题五、使用MyBatis5.1 创建库表createdatabasespringbootdefaultcharactersetutf8collateutf8_general_ci;createuserspring%identifiedbyspring#123;createuserspringlocalhostidentifiedbyspring#123;grantallprivilegesonspringboot.*tospring%identifiedbyspring#123;grantallprivilegesonspringboot.*tospringlocalhostidentifiedbyspring#123;flushprivileges;droptableifexistsstudent;createtablestudent(snoint(11)notnullauto_incrementcomment学号,snamevarchar(50)charactersetutf8collateutf8_general_cinotnullcomment姓名,ssexvarchar(2)charactersetutf8collateutf8_general_cinotnullcomment性别,primarykey(sno)usingbtree)engineinnodbauto_increment1charactersetutf8collateutf8_general_ci row_formatdynamic;insertintostudentvalues(1,KangKang,M);insertintostudentvalues(2,Mike,M);insertintostudentvalues(3,Jane,F);5.2 创建对应实体GetterSetterpublicclassStudentimplementsSerializable{privatestaticfinallongserialVersionUID-339516038496531943L;privateintsno;privateStringname;privateStringsex;}创建一个包含基本CRUD的StudentMapperComponentMapperpublicinterfaceStudentMapper{intadd(Studentstudent);intupdate(Studentstudent);intdeleteBysno(intsno);StudentqueryStudentBySno(intid);}StudentMapper的实现可以基于xml也可以基于注解。5.3 使用注解方式继续编辑StudentMapperComponentMapperpublicinterfaceStudentMapper{Insert(insert into student(sno,sname,ssex) values(#{sno},#{name},#{sex}))intadd(Studentstudent);Update(update student set sname#{name},ssex#{sex} where sno#{sno})intupdate(Studentstudent);Delete(delete from student where sno#{sno})intdeleteBysno(intsno);Select(select * from student where sno#{sno})Results(idstudent,value{Result(propertysno,columnsno,javaTypeInteger.class),Result(propertyname,columnsname,javaTypeString.class),Result(propertysex,columnssex,javaTypeString.class)})StudentqueryStudentBySno(intid);}简单的语句只需要使用Insert、Update、Delete、Select这4个注解即可动态SQL语句需要使用InsertProvider、UpdateProvider、DeleteProvider、SelectProvider等注解。具体可参考MyBatis官方文档http://www.mybatis.org/mybatis-3/zh/java-api.html。5.4 使用xml方式使用xml方式需要在application.yml中进行一些额外的配置mybatis: # type-aliases扫描路径 # type-aliases-package: # mapper xml实现扫描路径 mapper-locations: classpath:mapper/*.xml property: order: BEFORE六、测试接下来编写ServicepublicinterfaceStudentService{intadd(Studentstudent);intupdate(Studentstudent);intdeleteBysno(intsno);StudentqueryStudentBySno(intsno);}实现类Service(studentService)publicclassStudentServiceImplimplementsStudentService{AutowiredprivateStudentMapperstudentMapper;Overridepublicintadd(Studentstudent){returnthis.studentMapper.add(student);}Overridepublicintupdate(Studentstudent){returnthis.studentMapper.update(student);}OverridepublicintdeleteBysno(intsno){returnthis.studentMapper.deleteBysno(sno);}OverridepublicStudentqueryStudentBySno(intsno){returnthis.studentMapper.queryStudentBySno(sno);}}编写controllerRestControllerpublicclassTestController{AutowiredprivateStudentServicestudentService;RequestMapping(value/querystudent,methodRequestMethod.GET)publicStudentqueryStudentBySno(intsno){returnthis.studentService.queryStudentBySno(sno);}}启动项目访问http://localhost:8080/querystudent?sno1查看SQL监控情况可看到其记录的就是刚刚访问/querystudent得到的SQL。