什么是 MyBatis?
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
快速入门
mysql数据库测试数据
# 创建数据库
CREATE DATABASE test;
USE `test`;
# 创建表
CREATE TABLE `User` (
`name` varchar(255) DEFAULT NULL,
`age` int DEFAULT NULL,
`sex` int DEFAULT NULL,
`id` int NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
# 插入测试数据
insert into `User`(`name`,`age`,`sex`,`id`) values ('xdb',27,1,1);
基于注解
maven依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
配置文件
mybatis-config-01.xml
<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://172.28.149.239:3306/test?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
</configuration>
mysql6之后的驱动是mysql.cj.jdbc.Driver, MySQL5用的驱动是com.mysql.jdbc.Driver
创建映射对象
User.java
private Integer id;
private String name;
private Integer age;
private Integer sex;
...
编写mapper
UserMapper.java
public interface UserMapper {
@Select("SELECT id, name, age, sex FROM User WHERE id = #{id}")
public User selectByid(Integer id);
}
编写测试类
Demo01.java
String resource = "mybatis-config-01.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSessionFactory.getConfiguration().addMapper(UserMapper.class);
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.selectByid(1);
System.out.println(user);
}
xml配置
配置文件
mybatis-config-02.xml
<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://172.28.149.239:3306/test?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapping/UserMapper.xml"/>
</mappers>
</configuration>
比上面多了个mappers配置, 通过配置文件加载mapper, 而不需用注解方法的sqlSessionFactory.getConfiguration().addMapper(UserMapper.class); 加载mapper
编写mapper
UserMapper.java
public User selectById(Integer id);
编写mapping
UserMapper.xml, 文件位置与上面的mappers配置中保持一致, namespace与mapper一致, resultType和mapper的返回值类型一致, id和mapper.java中的方法一致
<mapper namespace="top.itkaoti.example02.mapper.UserMapper">
<select id="selectById" resultType="top.itkaoti.example01.po.User">
select * from User where id = #{id}
</select>
</mapper>
测试类
String resource = "mybatis-config-02.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.selectById(1);
System.out.println(user);
}
重要概念
SqlSessionFactoryBuilder: 用来创建了 SqlSessionFactory的实例, 一旦创建完成就可以释放。
SqlSessionFactory: 工厂类一般都是单例, 一旦被创建就应该在应用的运行期间一直存在
SqlSession: 每个线程都应该有它自己的 SqlSession 实例。SqlSession 的实例不是线程安全的, 每次操作后都应该关闭