Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

This article mainly describes the basic use of MyBatis. I will use a JDBC example at the beginning, and then make a simple analysis of such data operation process, and then summarize, and finally lead to the use of MyBaits.

JDBC way

Here is a simple JDBC database access case.

public class JdbcTest {

	public static final String URL = "JDBC: mysql: / / 127.0.0.1 / summer_test? useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false";
	public static final String USER = "root";
	public static final String PASSWORD = "root2020";

	public static void main(String[] args) throws Exception {
		//1. Load the driver
		Class.forName("com.mysql.jdbc.Driver");
		//2. Obtain the database connection
		Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
		//3. Operate database to implement add, delete, change and check
		Statement stmt = conn.createStatement();
		ResultSet rs = stmt.executeQuery("SELECT user_name, age FROM student");
		Rs.next () returns true if there is data
		while(rs.next()){
			System.out.println(rs.getString("user_name") +" 年龄:"+rs.getInt("age")); }}}Copy the code

Used to think

Operating a database through JDBC has the following problems:

  1. Database connections are created when in use, and released when not in use. Frequent connections are switched on and off, which wastes database resources and affects database performance. Solution: Use the database connection pool to manage database connections
  2. SQL statements are hardcoded in Java programs. Modifying SQL statements requires recompiling The Java code, which is not good for system maintenance. If SQL statements are stored in XML configuration files, the Java code does not need to be recompiled
  3. PreparedStatement to set parameters, placeholder positions and set parameter values, hard code, modify SQL statements do not need to recompile Java code solution: SQL statements and placeholder set parameter values in the XML configuration file
  4. When iterating the result set data from result, there is hard coding, and the fields of the obtained table are hard coded. Solution: The query result set is automatically mapped to Java objects

What is MyBatis?

MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping. MyBatis eliminates almost all of the JDBC code and the work of setting parameters and fetching result sets. MyBatis can configure and map primitive types, interfaces, and Java POJOs (Plain Old Java Objects) to records in the database via simple XML or annotations.

MyBatis structure

The use of MyBatis

The configuration file

<? 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> <settings> <! -- Print query statement --> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <! -- Environment configuration will be eliminated after integration with Springdefault="development">
		<environment id="development"> <! <transactionManager type="JDBC"/ > <! DataSource type= mybatis"POOLED"> <! --> <property name="driver" value="com.mysql.jdbc.Driver"/>
				<property name="url"
						  value="JDBC: mysql: / / 127.0.0.1 / summer_test? useUnicode=true& characterEncoding=utf8& serverTimezone=GMT%2B8& useSSL=false"/>
				<property name="username" value="root"/>
				<property name="password" value="root2020"/> </dataSource> </environment> </environments> <mappers> <! Mapper --> <mapper resource="com/summer/test/mybatis/mapper/OrderMapper.xml"/>
	</mappers>
</configuration>
Copy the code

Mapper.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.summer.test.mybatis.OrderMapper">
	<select id="selectOne" resultType="int">
		select 1
	</select>
</mapper>
Copy the code

Mapper interfaces

package com.summer.test.mybatis;

public interface OrderMapper {

	Integer selectOne(a);
}

Copy the code

The test file

package com.summer.test.mybatis;

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 java.io.IOException;

public class MyBaitsTest {

	public static void main(String[] args) throws IOException {

		SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
		SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml")); SqlSession session = sqlSessionFactory.openSession(); OrderMapper orderMapper = session.getMapper(OrderMapper.class); orderMapper.selectOne(); }}Copy the code

The resources

  • www.runoob.com/w3cnote/jdb…
  • Mybatis.org/mybatis-3/z…
  • www.cnblogs.com/shamo89/p/9…