引入 starter
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
配置模式
- 导入mybatis官方starter
- 编写mapper接口。标准@Mapper注解
- 编写sql映射文件并绑定mapper接口
- 在application.yaml中指定Mapper配置文件的位置,以及指定全局配置文件的信息 (建议;配置在mybatis.configuration)
mybatis
指定全局配置文件和SQL映射文件的路径
mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
配置文件写一个模板,configuration里的东西去通过mybatis.configuration改是一样的.
<?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>
</configuration>
现在有一个表
建立 对象进行映射
package com.oldataraxia.helloweb.bean;
import lombok.Data;
@Data
public class Student {
private Long id;
private String name;
private Long gender;
private Long grade;
private Long score;
}
定义操作接口
package com.oldataraxia.helloweb.servlet;
import com.oldataraxia.helloweb.bean.Student;
public interface StudentMapper {
public Student getStudent(Long id);
}
SQL映射文件, namespace改成接口路径, id
是接口方法名;
<?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.oldataraxia.helloweb.servlet.StudentMapper">
<select id="getStudent" resultType="com.example.demo2.bean.Student">
select * from Student where id = #{id}
</select>
</mapper>
service层实现一个service
@Service
public class StudentService {
@Autowired
StudentMapper studentMapper;
public Student getStudentById(Integer id){
return studentMapper.getStudent(id);
}
}
controller进行测试
@GetMapping("/student")
public Student getById(@RequestParam("id") Integer id){
return studentService.getStudentById(id);
}
在一个叫 demo2
的项目里…
注解模式
在Mapper里用 @select
的方式来写sql
太复杂的可以写到配置文件里面.
@Mapper
public interface StudentMapper {
@Select("select * from student where id=#{id}")
@Options(useGeneratedKeys = true, keyProperty = "id")
public Student getStudent(long id);
}
自增主键
最佳实践
- 引入mybatis-starter
- 配置application.yaml,指定mapper-locations的位置
- 写mapper接口,别忘了
@mapper
- 简单方法注解方式,复杂方法用配置文件