1、简介

• MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。
• MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。
• MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。

2、MyBatis历史

• 原是Apache的一个开源项目iBatis, 2010年6月这个项目由Apache Software Foundation 迁移到了Google Code,随着开发团队转投Google Code旗下, iBatis3.x正式更名为MyBatis ,代码于2013年11月迁移到Github(下载地址见后)。
• iBatis一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。 iBatis提供的持久层框架包括SQL Maps和Data Access Objects(DAO)

3、为什么要使用MyBatis?

• MyBatis是一个半自动化的持久化层框架。
• JDBC
– SQL夹在Java代码块里,耦合度高导致硬编码内伤
– 维护不易且实际开发需求中sql是有变化,频繁修改的情况多见
• Hibernate和JPA
– 长难复杂SQL,对于Hibernate而言处理也不容易
– 内部自动生产的SQL,不容易做特殊优化。
– 基于全映射的全自动框架,大量字段的POJO进行部分映射时比较困难。导致数据库性能下降。
• 对开发人员而言,核心sql还是需要自己优化
• sql和java编码分开,功能边界清晰,一个专注业务、一个专注数据。

4、去哪里找MyBatis

• https://github.com/mybatis/mybatis-3/

5、HelloWorld简单版

a、创建一张测试表

CREATE TABLE tbl_employee(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
last_name VARCHAR(255),
gender CHAR(1),
email VARCHAR(255)
);
INSERT INTO tbl_employee(last_name,gender,email)VALUES("张三",'1',"zhangsan@qq.com");

b、创建对应的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 + "]";
    }
}

c、创建MyBatis全局配置文件

  • MyBatis 的全局配置文件包含了影响 MyBatis 行为甚深的设置(settings)和属性(properties)信息、如数据库连接池信息等。指导着MyBatis进行工作。我们可以参照官方文件的配置示例。

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">
				<property name="driver" value="com.mysql.cj.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://localhost:3306/test" />
				<property name="username" value="root" />
				<property name="password" value="123456" />
			</dataSource>
		</environment>
	</environments>
	<!-- 将我们写好的sql映射文件(EmployeeMapper.xml)一定要注册到全局配置文件(mybatis-config.xml)中 -->
	<mappers>
		<mapper resource="EmployeeMapper.xml" />
	</mappers>
</configuration>

d、创建SQL映射文件

  • 映射文件的作用就相当于是定义Dao接口的实现类如何工作。这也是我们使用MyBatis时编写的最多的文件。

EmployeeMapper.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.xiaoqiu.EmployeeMapper">
    <!--
    namespace:名称空间;
    id:唯一标识
    resultType:返回值类型
    #{id}:从传递过来的参数中取出id值
     -->
    <select id="selectEmp" resultType="com.xiaoqiu.bean.Employee">
        select id, last_name lastName, email, gender
        from tbl_employee
        where id = #{id}
    </select>
</mapper>

e、测试

1、根据全局配置文件,利用SqlSessionFactoryBuilder创建SqlSessionFactory

String resource = “mybatis-config. xm1”;
InputStream inputStream = Resources. getResourceAsStream( resource) ;
SqlSessionFactory factory = new SqlSessionFactoryBuilder() . build(inputStream) ;

2、使用SqlSessionFactory获取sqlSession对象。一个SqlSession对象代表和数据库的一次会话。

SqlSession openSession = factory. openSession();

3、使用SqlSession根据方法id进行操作

try {
Employee employee = openSession.selectOne(“com.xiaoqiu.EmployeeMapper.selectEmp”, 1);
System.out.println(employee);
} finally {
openSession.close();
}

MyBatisTest

public class MyBatisTest {
	public SqlSessionFactory getSqlSessionFactory() throws IOException {
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		return new SqlSessionFactoryBuilder().build(inputStream);
	}

	/**
	 * 1、根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象 有数据源一些运行环境信息
	 * 2、sql映射文件;配置了每一个sql,以及sql的封装规则等。 
	 * 3、将sql映射文件注册在全局配置文件中
	 * 4、写代码:
	 * 		1)、根据全局配置文件得到SqlSessionFactory;
	 * 		2)、使用sqlSession工厂,获取到sqlSession对象使用他来执行增删改查
	 * 			一个sqlSession就是代表和数据库的一次会话,用完关闭
	 * 		3)、使用sql的唯一标志来告诉MyBatis执行哪个sql。sql都是保存在sql映射文件中的。
	 */
	@Test
	public void test() throws IOException {

		// 2、获取sqlSession实例,能直接执行已经映射的sql语句
		// sql的唯一标识:statement Unique identifier matching the statement to use.
		// 执行sql要用的参数:parameter A parameter object to pass to the statement.
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();

		SqlSession openSession = sqlSessionFactory.openSession();
		try {
														//id|namespace+id
			Employee employee = openSession.selectOne("com.xiaoqiu.EmployeeMapper.selectEmp", 1);
			System.out.println(employee);
		} finally {
			openSession.close();
		}
	}
}

控制台输出结果:

DEBUG 10-13 17:09:16,410 ==>  Preparing: select id, last_name lastName, email, gender from tbl_employee where id = ?   (BaseJdbcLogger.java:145) 
DEBUG 10-13 17:09:16,461 ==> Parameters: 1(Integer)  (BaseJdbcLogger.java:145) 
DEBUG 10-13 17:09:16,516 <==      Total: 1  (BaseJdbcLogger.java:145) 
Employee [id=1, lastName=张三, email=zhangsan@qq.com, gender=1]

Process finished with exit code 0

6、HelloWorld接口式编程

a、创建一个Dao接口

public interface EmployeeMapper {
	
	public Employee getEmpById(Integer id);

}

b、修改Mapper文件

<?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.xiaoqiu.dao.EmployeeMapper">
    <!--
    namespace:名称空间;指定为接口的全类名
    id:唯一标识
    resultType:返回值类型
    #{id}:从传递过来的参数中取出id值

    public Employee getEmpById(Integer id);
     -->
    <select id="getEmpById" resultType="com.xiaoqiu.bean.Employee">
        select id, last_name lastName, email, gender
        from tbl_employee
        where id = #{id}
    </select>
</mapper>

c、测试

1、使用SqlSession获取映射器进行操作
try {
//获取接口的实现类对象
//会为接口自动的创建一个代理对象,代理对象去执行增删改查方法
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
Employee employee = mapper.getEmpById(1);
System.out.println(mapper.getClass());
System.out.println(employee);
} finally {
openSession.close();
}

SqlSession
• SqlSession 的实例不是线程安全的,因此是不能被共享的。
• SqlSession每次使用完成后需要正确关闭,这个关闭操作是必须的
• SqlSession可以直接调用方法的id进行数据库操作,但是我们一般还是推荐使用SqlSession获取到Dao接口的代理类,执行代理对象的方法,可以更安全的进行类型检查操作

/**
 * 1、接口式编程
 * 	原生:		Dao		====>  DaoImpl
 * 	mybatis:	Mapper	====>  xxMapper.xml
 * 
 * 2、SqlSession代表和数据库的一次会话;用完必须关闭;
 * 3、SqlSession和connection一样都是非线程安全。每次使用都应该去获取新的对象。
 * 4、mapper接口没有实现类,但是mybatis会为这个接口生成一个代理对象。
 * 		(将接口和xml进行绑定)
 * 		EmployeeMapper empMapper =	sqlSession.getMapper(EmployeeMapper.class);
 * 5、两个重要的配置文件:
 * 		mybatis的全局配置文件:包含数据库连接池信息,事务管理器信息等...系统运行环境信息
 * 		sql映射文件:保存了每一个sql语句的映射信息:
 * 					将sql抽取出来。	
 */
public class MyBatisTest {
	

	public SqlSessionFactory getSqlSessionFactory() throws IOException {
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		return new SqlSessionFactoryBuilder().build(inputStream);
	}

	@Test
	public void test() throws IOException {
		// 1、获取sqlSessionFactory对象
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
		// 2、获取sqlSession对象
		SqlSession openSession = sqlSessionFactory.openSession();
		try {
			// 3、获取接口的实现类对象
			//会为接口自动的创建一个代理对象,代理对象去执行增删改查方法
			EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
			Employee employee = mapper.getEmpById(1);
			System.out.println(mapper.getClass());
			System.out.println(employee);
		} finally {
			openSession.close();
		}

	}

}

控制台输出结果:

DEBUG 10-13 18:10:47,687 ==>  Preparing: select id, last_name lastName, email, gender from tbl_employee where id = ?   (BaseJdbcLogger.java:145) 
DEBUG 10-13 18:10:47,740 ==> Parameters: 1(Integer)  (BaseJdbcLogger.java:145) 
DEBUG 10-13 18:10:47,787 <==      Total: 1  (BaseJdbcLogger.java:145) 
class com.sun.proxy.$Proxy4
Employee [id=1, lastName=张三, email=zhangsan@qq.com, gender=1]

Process finished with exit code 0
Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐