简介
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
ORM
orm:就是对象关系映射
- 对象:Java实体类对象
- 关系:关系型数据库
- 映射:两者关系
Java | 数据库 |
---|---|
类 | 表 |
属性 | 字段/列 |
对象 | 记录/行 |
只要提供了持久化类与表的映射关系,ORM框架在运行时就能参照映射文件的信息,把对象持久化到数据库中。当前ORM框架主要有五种:Hibernate(Nhibernate),iBatis,mybatis,EclipseLink,JFinal。
入门
项目目录
准备配置
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<?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>
<!--链接数据库配置-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/数据库名称?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai"/>
<property name="username" value="数据库账号"/>
<property name="password" value="数据库密码"/>
</dataSource>
</environment>
</environments>
<!--扫描的xml的包-->
<mappers>
<package name="com.aaa.sayhellomybatis.mapper"/>
</mappers>
</configuration>
数据库语句
CREATE TABLE `product` (
`id` bigint NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`price` decimal(10,2) DEFAULT NULL,
`version` int DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
代码
public interface ProductMapper {
int insertAll(Product product);
List<Product> selectall();
int updateById(@Param("id") Long id);
int deleteById(@Param("id") Long 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.aaa.sayhellomybatis.mapper.ProductMapper">
<resultMap id="BaseResultMap" type="com.aaa.sayhellomybatis.domain.Product">
<id property="id" column="id" jdbcType="BIGINT"/>
<result property="name" column="name" jdbcType="VARCHAR"/>
<result property="price" column="price" jdbcType="DECIMAL"/>
<result property="version" column="version" jdbcType="INTEGER"/>
</resultMap>
<sql id="Base_Column_List">
id,name,price,
version
</sql>
<insert id="insertAll">
insert into product
(id, name, price,
version)
values (#{id,jdbcType=NUMERIC}, #{name,jdbcType=VARCHAR}, #{price,jdbcType=DECIMAL},
#{version,jdbcType=NUMERIC})
</insert>
<select id="selectall" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from product
</select>
<delete id="deleteById">
delete
from product
where id = #{id,jdbcType=NUMERIC}
</delete>
<update id="updateById">
update product
set where
id = #{id,jdbcType=NUMERIC}
</update>
</mapper>
测试
@Test
public void testMybatis() throws IOException {
InputStream inputStream= Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
ProductMapper mapper = session.getMapper(ProductMapper.class);
List<Product> productList = mapper.selectall();
productList.forEach(System.out::println);
}
}
配置文件解析
参数解析
获取参数的方式${}和#{}
${}拼接字符串拼接,#{}占位占位符(自动加""),${}要用单引号
获取参数的情况
参数 | 方式 |
---|---|
单个参数 | 通过${}和#{}获取参数值 |
多个参数 | 通过${}和#{}获取键值对 |
实体类 | 通过${}和#{}获取属性值 |
使用@Parm注解
@Param("键名")值名--》{键名:值名}
int updateById(@Param("id") Long id);
各种查询功能
- 查询结果为一条
<select id="selectOneById" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from product
where
id = #{id,jdbcType=NUMERIC}
</select>
Product selectOneById(@Param("id") Long id);
- 查询结果为多条,使用list或者map接收
<select id="selectById" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from product
where
id = #{id,jdbcType=NUMERIC}
</select>
List<Product> selectById(@Param("id") Long id);
3.函数
模糊查询
like “%”#{参数}“%”
映射关系
一对一
- 为字段起别名(AS)
- 设置全局配置,将_自动映射为驼峰
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
- 使用resultMap
<resultMap id="BaseResultMap" type="com.aaa.sayhellomybatis.domain.Product">
<id property="id" column="id" jdbcType="BIGINT"/>
<result property="name" column="name" jdbcType="VARCHAR"/>
<result property="price" column="price" jdbcType="DECIMAL"/>
<result property="version" column="version" jdbcType="INTEGER"/>
</resultMap>
多对一
- 级联属性
<resultMap id="BaseResultMap" type="com.aaa.sayhellomybatis.domain.Product">
....
<result property="一的那一方关联字段 类名.属性" column="多的那一方f关联字段 类名.属性"/>
</resultMap>
- 通过
- 分布查询