基本概念
- MyBatis是支持定制化sql,存储过程以及高级映射的优秀的持久层框架
- MyBatis是一个半自动化的持久层框架
Hibernate的不足
- 内部自动生产的sql,不容易做优化处理
- 基于全映射的全自动框架,大量字段的POJO进行部分映射比较困难,导致数据库性能下降。对于开发人员而言,核心sql还是需要自己优化
下载地址
https://github.com/mybatis/mybatis-3/
创建一个简单的工程样例
创建数据库表单
- 创建数据库mybatis和tbl_employee表
CREATE DATABASE mybatis;
USE mybatis;
CREATE TABLE tbl_employee(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
last_name VARCHAR(255),
gender CHAR(1),
email VARCHAR(255)
)
- 添加一行数据
创建Java工程,实现对数据库的操作
新建一个pojo类作为表单项对应的类
- 创建一个Java工程,新建一个Java类作为表单项对应的类,employee.class
package com.mybatis.bean;
/**
* @author ningqian
* @create -05-20 21:10
*/
/**
* 创建一个JavaBean,对应数据库的表单项
*/
public class Employee {
private Integer id;
private String lastName;
private String email;
private String gender;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", gender='" + gender + '\'' +
'}';
}
}
资源配置文件夹
创建一个文件夹,名为config,存放配置文件,将该文件夹作为资源文件夹,选中该文件夹-右键-将其作为源文件夹
导入相关的包及打印日志
- 下载地址:https://wwa.lanzoui.com/ix6Ovpc1p8b
三个包:数据库驱动、mybatis、日志包
- 数据库驱动要与自己电脑上的数据库版本对应,我的mysql版本为8.0,所以导入的驱动为8.0
- 将压缩包中的log4j.xml日志打印配置文件放到config文件夹
创建全局配置文件
在config目录下新建一个xml文件作为全局配置文件,名为mybatis-config.xml
<?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">
<!--修改连接配置,注意driver和url对于不同的数据库驱动写法不同,这里是8.0版本的驱动-->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="777777"/>
</dataSource>
</environment>
</environments>
<!--将sql映射文件注册到全局配置中-->
<mappers>
<mapper resource="EmployeeMapper.xml"/>
</mappers>
</configuration>
创建sql映射文件
在config目录下新建一个xml文件作为sql映射文件,然后将该文件注册到全局配置文件中
<?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">
<!--作为sql语句的映射配置文件,其实就是在这里写sql语句-->
<mapper namespace="com.mybatis.EmployeeMapper">
<!--名称空间:可以自定义名称
id:唯一标识
resultType:查询返回类型,值为表单项对应类的全类名
#{id}:从传递过来的参数中取出id值
-->
<!--1. 查询某个id的表单项,如果表单映射类的字段和数据库表单的字段名字不一致,必须要给该字段加别名-->
<select id="selectEmp" resultType="com.mybatis.bean.Employee">
select id,last_name lastName,gender ,email from tbl_employee where id = #{id}
</select>
</mapper>
创建查询测试类
创建查询测试类MyBatisTest
package com.mybatis.test;
import com.mybatis.bean.Employee;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
/**
* @author ningqian
* @create -05-20 21:55
*/
/**
* 根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象
*
*/
public class MyBatisTest {
@Test
public void test() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
//获取一个sqlSession对象,可以直接执行已经映射的sql语句
SqlSession openSession = sqlSessionFactory.openSession();
//参数1 sql的唯一标识:使用名称空间+sql语句的id
//参数2 sql语句中需要传入的参数
try{
Employee employee = openSession.selectOne("com.mybatis.EmployeeMapper.selectEmp", 1);
System.out.println(employee);
}finally {
openSession.close();
}
}
}
测试结果
接口式编程
mybatis会将接口和sql映射文件动态绑定
- 编写一个接口EmployeeMapper
package com.mybatis.sql;
import com.mybatis.bean.Employee;
/**
* @author ningqian
* @create -05-21 9:46
*/
public interface EmployeeMapper {
public Employee getEmpById(Integer id);
}
- 将接口与sql映射文件EmployeeMapper绑定
(1)将名称空间修改为接口的路径
(2)将查询sql语句的id修改为接口的中的方法名
3. 测试方法
@Test
public void testInterface() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
SqlSession openSession = null;
try{
//获取一个sqlSession对象,可以直接执行已经映射的sql语句
openSession = sqlSessionFactory.openSession();
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
//mybatis自动创建代理对象
Employee empById = mapper.getEmpById(1);
System.out.println(empById);
}finally {
openSession.close();
}
}
小结
- SqlSession代表和数据库的一次会话,用完必须关闭
- SqlSession和Connection一样都是非线程安全的,每次使用都应该去获取新的对象