什么是MyBatis?
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。
MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
快速入门
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/person(#数据库表名字)
spring.datasource.username=root(#数据库用户名)
spring.datasource.password=123456(#数据库密码)
4.创建实体类(Person),并创建相应的数据表
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.resource中添加映射文件 com.example.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.example.mapper.PersonMapper">
<select id="find" resultType="com.example.entity.Person">
select *
from person;
</select>
</mapper>
8.测试
statement详解
Mybatis的核心是SQL,一个statement代表着一个SQL,因此,statement的配置即是我们通过Mybatis操作数据库的核心。
statement分为四个标签:<insert>、<delete>、<update>
、<select>分别代表对数据的增删改查。
标签中定义的便是原生的SQL语句,需要新掌握的是标签上的属性:
id
每个statement都有,且为必选属性,id为statement提供唯一标识,以保证该statement可以被成功定位并执行。不能重复。
resultType
只有select语句有该属性,代表SQL返回结果的类型,查询用户可以指定为entity.Person类型
<select id="findAll" resultType="com.example.entity.Person">
select * from person
</select>
resultMap
只有select语句有,当SQL结果集不能自动映射到实体类属性时使用,
比如数据库字段为person_id,而Person类中属性为personId,此时Mybatis不能自动映射,需要手动映射。
以下为实例,id标签指定主键属性,result标签指定普通属性,column属性对应表中字段名,property属性对应类中属性名,autoMapping自动映射。可选
<resultMap id="personResultMap" type="com.example.entity.Person">
<id column="id" property="id"/>
<!-- <result column="name" property="name"/>-->
<!-- <result column="age" property="age"/>-->
<result column="love_color" property="loveColor"/>
</resultMap>
<select id="findAll3" resultMap="personResultMap">
select * from person
</select>
insert插入
<insert id="insert">
insert into person(id,name,age,love_color)
values
(null,"zl",26,"紫色")
</insert>
update更新
<update id="updateById">
update person
set name ='7仔'
where id = 7
</update>
delete删除
<delete id="deleteById">
delete
from person
where id = 204
</delete>