跳转到目录
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jdbcartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.1.2version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
<version>1.1.20version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
<exclusions>
<exclusion>
<groupId>org.junit.vintagegroupId>
<artifactId>junit-vintage-engineartifactId>
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:
username: root
password: 1111
url: jdbc:mysql://localhost:3306/springboot_mybatis
driver-class-name: com.mysql.jdbc.Driver
initialization-mode: always
# 数据源更改为druid
type: com.alibaba.druid.pool.DruidDataSource
druid:
# 连接池配置
# 配置初始化大小、最小、最大
initial-size: 1
min-idle: 1
max-active: 20
# 配置获取连接等待超时的时间
max-wait: 3000
validation-query: SELECT 1 FROM DUAL
test-on-borrow: false
test-on-return: 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: true
url-pattern: /*
exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
stat-view-servlet:
enabled: true
url-pattern: /druid/*
login-username: admin
login-password: root
allow: 127.0.0.1
schema:
- classpath:sql/department.sql
- classpath:sql/employee.sql
跳转到目录
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
@RestController
public class DeptController {
@Resource
private DepartmentMapper departmentMapper;
@GetMapping("/dept/{id}")
public Department getDepartment(@PathVariable("id") Integer id) {
return departmentMapper.getDeptById(id);
}
@GetMapping("/dept")
public Department insertDept(Department department) {
int count = departmentMapper.insertDept(department);
if (count > 0) {
System.out.println("插入数据成功");
}
return department;
}
访问:http://localhost:8080/dept?departmentName=gzy
添加一条数据
访问:http://localhost:8080/dept/1
获取数据
开启驼峰命名法
我们的实体类和表中的列名一致,一点问题也没有
我们把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.Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer() {
@Override
public void customize(Configuration configuration) {
// 开启驼峰命名映射
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
使用@mapper
注解的类可以被扫描到容器中,但是每个Mapper都要加上这个注解就是一个繁琐的工作,能不能直接扫描某个包下的所有Mapper接口呢,当然可以,在springboot启动类上加上@MapperScan
@MapperScan(“cn.clboy.springbootmybatis.mapper”)
跳转到目录
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
settings>
configuration>
@Mapper 或者 @MapperScan将接口扫描装配到容器中
public interface EmployeeMapper {
public Employee getEmpById(@Param("id") Integer id);
public void insertEmp(Employee employee);
}
<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>
# 加载mybati的全局配置文件
mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
@RestController
public class EmpController {
@Resource
private EmployeeMapper employeeMapper;
@GetMapping("/emp/{id}")
public Employee getEmp(@PathVariable("id") Integer id) {
return employeeMapper.getEmpById(id);
}
}