1. Quick start

0. Review jdbc operation database

  • Create a database instance in the MySQL database mybatisand create a table in it
CREATE TABLE employee(
	id INT(11) PRIMARY KEY AUTO_INCREMENT,
	last_name VARCHAR(255),
	gender CHAR(1),
	email VARCHAR(255)
);
-- 再插进一条随意数据,用于测试
INSERT INTO employee VALUES(1, 'tina', '女', '[email protected]');
  • Create a Maven project and add dependencies

pom.xml

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>6.0.6</version>
</dependency>

Test JDBC

@Test
    public void testJDBC() {
    
    
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
    
    
            //1、注册数据库驱动
            DriverManager.registerDriver(new Driver());
            //2、获取数据库连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=CTT", "root", "123456");
            //3、获取传输器对象
            statement = connection.createStatement();
            //4、利用传输器传输sql语句到数据库中执行,获取结果集对象
            resultSet = statement.executeQuery("select *  from employee");
            //预处理语句:作用:可以减轻数据库的负担,提高访问数据库的速度
            //statement = connection.prepareStatement("select *  from user");
            //5、遍历结果集获取查询结果
            while (resultSet.next()) {
    
    
                String id = resultSet.getString("id");
                String lastName = resultSet.getString("last_name");
                String gender = resultSet.getString("gender");
                String email = resultSet.getString("email");
                System.out.println("id: " + id);
                System.out.println("userId: " + lastName);
                System.out.println("userHead: " + gender);
                System.out.println("createTime: " + email);
            }
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            try {
    
    
                //6、关闭资源
                resultSet.close();
                statement.close();
                connection.close();
            } catch (SQLException e) {
    
    
                e.printStackTrace();
            }
        }
    }

1. Quick start

1.1 Introduction

What is MyBatis

  • MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping .
  • MyBatis avoids almost all JDBC code and manually setting parameters and getting result sets.
  • MyBatis can use simple XML or annotations for configuration and original mapping, and map interfaces and Java POJOs (Plain Old Java Objects, ordinary Java objects) into records in the database

History of MyBatis

  • It was originally an open source project of Apache iBatis. In June 2010, the project was migrated from Apache Software Foundation to Google Code. As the development team transferred to Google Code, iBatis3.x officially changed its name to MyBatis, and the code was migrated to Github in November 2013. (See below for the download address).
  • The word iBatis comes from the combination of "internet" and "abatis", which is a Java-based persistence layer framework. The persistence layer framework provided by iBatis includes SQL Maps and Data Access Objects (DAO)

Why use MyBatis?

  • JDBC
    • SQL is caught in the Java code block, and the high degree of coupling leads to hard-coded internal damage
    • It is not easy to maintain and sql changes in actual development requirements, and frequent modifications are common

img

  • Hibernate and JPA
    – long and difficult complex SQL, and it is not easy for Hibernate to handle
    – the internal automatically generated SQL is not easy to do special optimization.
    – Based on the full-mapping fully automatic framework, it is difficult to partially map POJOs with a large number of fields, resulting in a decline in database performance.

img

  • MyBatis is a semi-automatic persistence layer framework.
    • For developers, the core SQL still needs to be optimized by itself
    • The sql and java codes are separated, and the functional boundaries are clear. One focuses on business and the other focuses on data.

img

1.2. Download

MyBatisDownload

MyBatis official website

1.3.HelloWorld

  • Add mybatis dependency

pom.xml

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.1</version>
</dependency>

  • Create the corresponding JavaBean

Employee.java

public class Employee {
    
    
	
	private Integer id;
	private String lastName;
	private String email;
	private String gender;

	//getter and setter and toString()
}
  • Create mybatis configuration file, sql mapping file
    • The global configuration file of MyBatis contains settings and properties information that deeply affect the behavior of MyBatis, such as database connection pool information, etc. Guide MyBatis to work. We can refer to the configuration example in the official document.
    • The role of the mapping file is equivalent to defining how the implementation class of the Dao interface works. This is also the file we write the most when using MyBatis .

mybatis global configuration file

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/mybatis?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=CTT" />
				<property name="username" value="root" />
				<property name="password" value="123456" />
			</dataSource>
		</environment>
	</environments>
	<!-- 将我们写好的sql映射文件(EmployeeMapper.xml)一定要注册到全局配置文件(mybatis-config.xml)中 -->
	<mappers>
		<mapper resource="c01/EmployeeMapper.xml" />
	</mappers>
</configuration>

sql mapping file

EmployeeMapper.xml

<mapper namespace="abc">
<!-- 
namespace:名称空间;通常指定为接口的全类名
id:唯一标识
resultType:返回值类型
#{id}:从传递过来的参数中取出id值

public Employee getEmpById(Integer id);
 -->
	<select id="getEmpById" resultType="club.coderhome.c01.helloworld.bean.Employee">
		select id,last_name lastName,email,gender from employee where id = #{id}
	</select>
</mapper>
  • test

HelloWorldTest.java

public class HelloWorldTest {
    
    

	public SqlSessionFactory getSqlSessionFactory() throws IOException {
    
    
		String resource = "c01/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映射文件中的。
	 * 
	 * @throws IOException
	 */
	@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 {
    
    
			Employee employee = openSession.selectOne(
					"abc.getEmpById", 1);
			System.out.println(employee);
		} finally {
    
    
			openSession.close();
		}

	}

}

1.4. Interface programming

Interface programming will be mainly used in the future

HelloWorld-interface programming

  • Create a Dao interface

EmployeeMapper.java

import club.coderhome.c01.helloworld.bean.Employee;

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

}
  • Modify Mapper file (namespace, id, returnType)

EmployeeMapper2.xml

<mapper namespace="club.coderhome.c01.helloworld.dao.EmployeeMapper">
<!-- 
namespace:名称空间;指定为接口的全类名
id:唯一标识
resultType:返回值类型
#{id}:从传递过来的参数中取出id值

public Employee getEmpById(Integer id);
 -->
	<select id="getEmpById" resultType="club.coderhome.c01.helloworld.bean.Employee">
		select id,last_name lastName,email,gender from employee where id = #{id}
	</select>
</mapper>
  • test

HelloWorldTest.java

@Test
public void test01() 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();
	}

}

1.5. Summary

  1. interface programming
    • Native: Dao ====> DaoImpl
    • mybatis: Mapper ====> xxMapper.xml
  2. SqlSession represents a session with the database; it must be closed when it is used up;
  3. Like connection, SqlSession is not thread-safe. Every time you use it, you should get a new object.
  4. The mapper interface does not have an implementation class, but mybatis will generate a proxy object for this interface.
    (bind the interface with xml)EmployeeMapper empMapper = sqlSession.getMapper(EmployeeMapper.class);
  5. Two important configuration files:
    • The global configuration file of mybatis: contains database connection pool information, transaction manager information, etc... system operating environment information
    • sql mapping file: saves the mapping information of each sql statement: extracts sql.

Guess you like

Origin blog.csdn.net/qq_29216579/article/details/130986119
Recommended