MyBaties概述
mybaties是一款优秀的持久层ORM框架,它支持定制化SQL、存储过程以及高级映射。
Mybatis执行流程
Configration会去找全局配置文件mybatis.xml,然后sesssion工厂去找sqlsession。
Sqlsession就是myBatis中最核心的了。它去加载mappedStatment。然后去执行TransAction。
Mybatis快速入门
1.创建SpringBoot项目
2.引入依赖
<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>
3.在application.properties
中配置数据库连接参数
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/表明
spring.datasource.username=用户名
spring.datasource.password=密码
4.创建实体类person,并创建数据库
“加个注解@Data可以不用手动构建getters和setters"
public class Person {
private Integer id;
private String name;
private Integer age;
// getters and setters
}
5.创建PersonController
@Controller
public class PersonController {
@Autowired
private PersonMapper personMapper;
@GetMapping("/find")
@ResponseBody
public List<Person> find() {
List<Person> list = personMapper.findAll();
System.out.println(list);
return list;
}
}
6.创建com.codingfuture.mapper.PersonMapper
接口
@Mapper
public interface PersonMapper {
List<Person> find();
}
7.resources
中添加映射文件com.codingfuture.mapper.PersonMapper.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.codingfuture.mapper.PersonMapper">
<select id="find" resultType="com.codingfuture.entity.Person">
select *
from person;
</select>
</mapper>
小结:
1.编写mapper.xml,书写SQL,并定义好SQL的输入参数,和输出参数
2.编写全局配置文件,配置数据源,以及要加载的mapper.xml文件