SpringBoot整合Mbatis

Posted 从入门到放弃

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot整合Mbatis相关的知识,希望对你有一定的参考价值。

bean 文件:

public class Employee {
private Integer id;
private String lastName;
private Integer gender;
private String email;
private Integer dId;

}

public class Department {
private Integer id;
private String departmentName;

}

config配置文件://通过注解配置驼峰式

@Configuration

public class MyBatisConfig {

@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer(){
@Override
public void customize(Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}

 controller:

@RestController
public class DeptController {
@Autowired
DepartmentMapper departmentMapper;

@Autowired
EmployeeMapper employeeMapper;

@GetMapping("/dept/{id}")
public Department getDepartment(@PathVariable("id") Integer id){
return departmentMapper.getDeptById(id);
}

@GetMapping("/dept")
public Department insertDept(Department department){
departmentMapper.insertDept(department);
return department;
}

@GetMapping("/emp/{id}")
public Employee getEmp(@PathVariable("id") Integer id){
return employeeMapper.getEmpById(id);
}
}

 mapper:

//指定这是一个操作数据库的mapper
//@Mapper
public interface DepartmentMapper {

@Select("select * from department where id=#{id}")
public Department getDeptById(Integer id);

@Delete("delete from department where id=#{id}")
public int deleteDeptById(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);
}
//@Mapper或者@MapperScan将接口扫描装配到容器中
public interface EmployeeMapper {

public Employee getEmpById(Integer id);

public void insertEmp(Employee employee);
}

 

启动类:

@MapperScan(value="com.hourui.mapper")
@SpringBootApplication
public class SpringbootmybatisApplication {

public static void main(String[] args) {
SpringApplication.run(SpringbootmybatisApplication.class, args);
}

}

application.yml:

spring:
datasource:
# 数据源基本配置
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis
type: com.alibaba.druid.pool.DruidDataSource
# 数据源其他配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,\'wall\'用于防火墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
mybatis:
# 指定全局配置文件位置
config-location: classpath:mybatis/mybatis-config.xml
# 指定sql映射文件位置
mapper-locations: classpath:mybatis/mapper/*.xml

# schema:
# - classpath:sql/department.sql
# - classpath:sql/employee.sql

mybatis-config.xml:

<?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>
</configuration>

EmployeeMapper.xml:

 

<?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.hourui.mapper.EmployeeMapper">
<!-- public Employee getEmpById(Integer id);

public void insertEmp(Employee employee);-->
<select id="getEmpById" resultType="com.hourui.bean.Employee">
SELECT * FROM employee WHERE id=#{id}
</select>

<insert id="insertEmp">
INSERT INTO employee(lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId})
</insert>
</mapper>

建表sql:

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for department
-- ----------------------------
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`departmentName` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for employee
-- ----------------------------
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`lastName` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`gender` int(2) DEFAULT NULL,
`d_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

 

完结!!!

以上是关于SpringBoot整合Mbatis的主要内容,如果未能解决你的问题,请参考以下文章

springboot Thymeleaf 整合

mbatis_逆向工程

spring boot 整合 redis

Mbatis——动态SQL

Mbatis逆向工程常遇错误

Mbatis是什么?怎么运行?