Springboot 2.x 整合 Mybatis
一、创建工程
MySQL Driver 的作用是帮我们注册驱动,之前做 JDBC 整合的时候导入 JDBC API,它的作用是会帮我们配置数据源,但是我们这里却没有选择 JDBC API 模块,难道是不需要配置数据源吗,其实不是的,我们选择 MyBatis Framework 模块,它会帮我们将 JDBC 也一起导入进来
引入的依赖如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version> 2.1 . 4 </version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> // 数据源使用 Druid ,不再使用 Springboot 默认的数据源 <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version> 1.2 . 3 </version> </dependency> |
创建完成之后注意,我们发现 MyBatis 依赖的命名和其他库的命名不太一样,其它的依赖都是以 spring-xx 开头的,而它是以 mybatis 开头的,是的,这个整合 jar 包并不是 springboot 自己的,这表示该 starter 是由第三方提供的,就像 Druid 数据源一样,也是第三方的.
二、项目结构
1、实体类(User)
1 2 3 4 5 6 7 8 | // 实体类,省略 set / get 方法 public class User { private Integer id; private String username; private String password; private String gender; private Date birthday; } |
2、Mapper 接口(UserMapper)
1 2 3 4 5 6 7 8 9 10 | // 运行时生成对应的接口实现类 @Mapper // 将该组件加入到 Spring 容器中 @Repository public interface UserMapper { public abstract Integer insertUser(User user); public abstract List<User> selectAll(); } |
这里要注意一下 @Mapper注解, @Mapper 注解添加位置在接口类上面它的作用是在运行时会生成相应的接口实现类,这种方法也是官方推荐使用的!这里只是测试整合 mybatis 编写一个 Mapper 接口即可,如果有需求要很多接口都要变成实现类,那么需要在每个接口类上加上 @Mapper 注解,比较麻烦,要解决这个问题可以使用 @MapperScan 注解.简单点说 @MapperScan 注解就是指定要扫描哪些包下的 Mapper 接口
1 2 3 4 5 6 7 8 | // com.springboot.mybatis.mapper 包下的所有接口都在运行时可以生成实现类 @MapperScan ( "com.springboot.mybatis.mapper" ) @SpringBootApplication public class MybatisApplication { public static void main(String[] args) { SpringApplication.run(MybatisApplication. class , args); } } |
3、application.properties
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | ########################### 数据库属性 ########################### spring.datasource.username=root spring.datasource.password= 123456 spring.datasource.url=jdbc:mysql: //192.168.229.131:3308/mybatis spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver ########################### Druid 数据源配置 ########################### # 配置当前要使用的数据源的操作类型,如果不配置就使用 springboot 默认的数据源 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource # 进行数据库链接池的配置,数据库最小维持连接数 spring.datasource.dbcp2.min-idle= 1 # 数据库初始化提供的连接数 spring.datasource.dbcp2.initial-size= 1 # 数据库最大维持连接数 spring.datasource.dbcp2.max-total= 1 ########################### MyBatis 配置文件 ########################### # 指定全局配置文件的位置 mybatis.config-location=classpath:mybatis-config/mybatis-global.xml # 指定 sql 映射文件的位置 mybatis.mapper-locations=classpath:mybatis-config/mapper/*.xml # com.springboot.mybatis.entity 包下的所有实体类都开启别名,当然也可以在 mybatis 的全局配置文件中开启 # mybatis.type-aliases- package =com.springboot.mybatis.entity |
4、mybatis 全局配置文件(mybatis-global.xml)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?xml version= "1.0" encoding= "UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration> <settings> <!--开启驼峰命名规则--> <setting name= "mapUnderscoreToCamelCase" value= "true" /> </settings> <typeAliases> <!-- com.mybatis.entity 包下的所有实体类都开启别名--> < package name= "com.springboot.mybatis.entity" ></ package > </typeAliases> </configuration> |
5、Mapper 映射文件(UserMapper.xml)
1 2 3 4 5 6 7 8 9 10 11 12 | <?xml version= "1.0" encoding= "UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace= "com.springboot.mybatis.mapper.UserMapper" > <insert id= "insertUser" useGeneratedKeys= "true" keyProperty= "id" > INSERT INTO user VALUES ( null ,#{username},#{password},#{gender},#{birthday}) </insert> <select id= "selectAll" resultType= "User" > SELECT * FROM user </select> </mapper> |
6、DruidConfig.java (使用 Druid 作为数据源,废弃 Springboot 默认的数据源,并对 SQL 进行监控)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | @Configuration public class DruidConfig { @Bean // 与 spring 的配置文件 application.properties 中前缀为 spring.datasource 的标签进行属性绑定 @ConfigurationProperties (prefix = "spring.datasource" ) public DruidDataSource druidDataSource() { return new DruidDataSource(); } // 配置 Druid 的监控 // 1、配置一个管理后台的 Servlet @Bean public ServletRegistrationBean statViewServlet() { ServletRegistrationBean bean = new ServletRegistrationBean( new StatViewServlet(), "/druid/*" ); Map<String, String> initParams = new HashMap<>(); initParams.put( "loginUsername" , "admin" ); initParams.put( "loginPassword" , "123456" ); initParams.put( "allow" , "" ); //默认就是允许所有访问 initParams.put( "deny" , "192.168.15.21" ); bean.setInitParameters(initParams); return bean; } //2、配置一个 web 监控的 filter @Bean public FilterRegistrationBean webStatFilter() { FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter( new WebStatFilter()); Map<String, String> initParams = new HashMap<>(); initParams.put( "exclusions" , "*.js,*.css,/druid/*" ); bean.setInitParameters(initParams); bean.setUrlPatterns(Arrays.asList( "/*" )); return bean; } } |
三、测试类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | @RestController public class HelloController { @Autowired private UserMapper userMapper; @GetMapping ( "/mybatis/insert" ) public String insert(Integer id) { User user = new User(); user.setUsername( "xiaomaomao" ); user.setPassword( "xiaomaomao123" ); user.setGender( "female" ); user.setBirthday( new Date()); Integer insertId = userMapper.insertUser(user); System.out.println(user.getId()); return insertId.toString(); } @GetMapping ( "/mybatis/selectAll" ) public String select() { List<User> userList = userMapper.selectAll(); return userList.toString(); } } |
四、访问 Druid 监控后台
http://localhost:8080/druid
账号密码为 admin / 123456 (Druid 管理后台的 Servlet 中配置的)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?