SpringBoot——SpringBoot整合MyBatis(注解、XML配置)
目录
一、SpringBoot整合MyBatis
引入依赖
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><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.2</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.20</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency></dependencies>
依赖关系
项目构建
1、在resources下创建department.sql
和employee.sql
,项目启动时创建表(在数据库中自动生成)
schema: - classpath:sql/department.sql - classpath:sql/employee.sql
2、实体类
public class Department {private Integer id;private String departmentName; // 省略 getter/setter 方法}
public class Employee {private Integer id;private String lastName;private Integer gender;private String email;private Integer dId;// 省略 getter/setter 方法}
3、配置文件
spring: datasource:useame: rootpassword: 1111url: jdbc:mysql://localhost:3306/springboot_mybatisdriver-class-name: com.mysql.jdbc.Driverinitialization-mode: always# 数据源更改为druidtype: com.alibaba.druid.pool.DruidDataSourcedruid: # 连接池配置 # 配置初始化大小、最小、最大 initial-size: 1 min-idle: 1 max-active: 20 # 配置获取连接等待超时的时间 max-wait: 3000 validation-query: SELECT 1 FROM DUAL test-on-borrow: false test-on-retu: false test-while-idle: true pool-prepared-statements: true time-between-eviction-runs-millis: 60000 min-evictable-idle-time-millis: 300000 filters: stat,wall,slf4j # 配置web监控,默认配置也和下面相同(除用户名密码,enabled默认false外),其他可以不配 web-stat-filter:enabled: trueurl-patte: /*exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*" stat-view-servlet:enabled: trueurl-patte: /druid/*login-useame: adminlogin-password: rootallow: 127.0.0.1schema: - classpath:sql/department.sql - classpath:sql/employee.sql
二、Mybatis增删改查(使用注解方式)
- 创建
mapper
接口
/** * Description: * * @author zygui * @date 2020/4/17 16:10 */// 指定这是一个操作数据库的mapper@Mapper // 这里必须要添加这个Mapper注解; 也可以在主启动类上统一通过@MapperScan(value="con.zy.mapper")来扫描public interface DepartmentMapper {@Select("SELECT * FROM department WHERE id = #{id}")public Department getDeptById(@Param("id") Integer id);@Delete("DELETE FROM department WHERE id = #{id}")public int deleteDeptById(@Param("id") Integer id);@Options(useGeneratedKeys = true, keyProperty = "id")@Insert("INSERT INTO department(department_name) VALUES(#{departmentName})")public int insertDept(Department department);@Update("UPDATE department SET department_name = #{departmentName} WHERE id = #{id}")public int updateDept(Department department);}
- 创建
Controller
@RestControllerpublic class DeptController {@Resourceprivate DepartmentMapper departmentMapper;@GetMapping("/dept/{id}")public Department getDepartment(@PathVariable("id") Integer id) {retu departmentMapper.getDeptById(id);}@GetMapping("/dept")public Department insertDept(Department department) {int count = departmentMapper.insertDept(department);if (count > 0) {System.out.println("插入数据成功");}retu department;}
-
访问:
http://localhost:8080/dept?departmentName=gzy
添加一条数据访问:
http://localhost:8080/dept/1
获取数据
Mybatis配置
开启驼峰命名法
我们的实体类和表中的列名一致,一点问题也没有
我们把department表的departmentName列名改为department_name看看会发生什么
访问:http://localhost:8080/dept/1获取数据
[{“id”:1,“departmentName”:null}]
由于列表和属性名不一致,所以就没有封装进去,我们表中的列名和实体类属性名都是遵循驼峰命名规则的,可以开启mybatis的开启驼峰命名配置
# 开启驼峰映射mybatis: configuration:map-underscore-to-camel-case: true
然后重启项目,重新插入数据,再查询就发现可以封装进去了
也可以通过向spring容器中注入org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer的方法设置mybatis参数
@org.springframework.context.annotation.Configurationpublic class MyBatisConfig {@Beanpublic ConfigurationCustomizer configurationCustomizer(){retu new ConfigurationCustomizer() {@Overridepublic void customize(Configuration configuration) {// 开启驼峰命名映射configuration.setMapUnderscoreToCamelCase(true);}};}}
Mapper扫描
使用@mapper
注解的类可以被扫描到容器中,但是每个Mapper都要加上这个注解就是一个繁琐的工作,能不能直接扫描某个包下的所有Mapper接口呢,当然可以,在springboot启动类上加上@MapperScan
@MapperScan(“cn.clboy.springbootmybatis.mapper”)
三、Mybatis增删改查(XML配置方式)
- 创建mybatis全局配置文件
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><!-- 开启数据库中列名和pojp的驼峰命名映射 --><settings><setting name="mapUnderscoreToCamelCase" value="true"/></settings></configuration>
- 创建EmployeeMapper接口
@Mapper 或者 @MapperScan将接口扫描装配到容器中public interface EmployeeMapper {public Employee getEmpById(@Param("id") Integer id);public void insertEmp(Employee employee);}
- 创建EmployeeMapper.xml映射文件
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.zy.mapper.EmployeeMapper"><select id="getEmpById" resultType="com.zy.pojo.Employee">SELECT * FROM employee WHERE id = #{id};</select><insert id="insertEmp">INSERT INTO employee (lastName, email, gender, d_id) VALUSE (#{lastName}, #{email}, #{gender}, #{dId})</insert></mapper>
- 配置文件(application.yaml)中指定配置文件和映射文件的位置
# 加载mybati的全局配置文件mybatis: config-location: classpath:mybatis/mybatis-config.xml mapper-locations: classpath:mybatis/mapper/*.xml
- Controller
@RestControllerpublic class EmpController { @Resourceprivate EmployeeMapper employeeMapper;@GetMapping("/emp/{id}")public Employee getEmp(@PathVariable("id") Integer id) {retu employeeMapper.getEmpById(id);}}
- 测试
作者:white camel
来源链接:https://blog.csdn.net/m0_37989980/article/details/105588234
版权声明:
1、JavaClub(https://www.javaclub.cn)以学习交流为目的,由作者投稿、网友推荐和小编整理收藏优秀的IT技术及相关内容,包括但不限于文字、图片、音频、视频、软件、程序等,其均来自互联网,本站不享有版权,版权归原作者所有。
2、本站提供的内容仅用于个人学习、研究或欣赏,以及其他非商业性或非盈利性用途,但同时应遵守著作权法及其他相关法律的规定,不得侵犯相关权利人及本网站的合法权利。
3、本网站内容原作者如不愿意在本网站刊登内容,请及时通知本站(javaclubcn@163.com),我们将第一时间核实后及时予以删除。