meet mybatis

The core components of mybatis are divided into four parts:

1. SqlSessionFactorybuilder (constructor): It will generate SqlSessionFactory according to the configuration in the configuration file. Of course, if you use the code to create it, it can also be achieved, but it is usually a good choice for extensibility to create a configuration file; it Creating a SqlSessionFactory is built step-by-step through the Builder pattern.

2. SqlSessionFactory (factory interface): use the factory pattern to generate SqlSession;

3. SqlSession (session): It is an interface that can send sql execution return results, or obtain Mapper;

4. SQL Mapper (mapper): a newly designed component of Mybatis, which consists of a Java interface and an XML file (or annotation), and needs to give the corresponding sql and mapping rules. It is responsible for sending sql to execute and returning the result.

Note: Both the mapper and SqlSession can send sql to the database for execution, but using Mapper interface programming can eliminate the functional code brought by SqlSession and improve readability; SqlSession sends sql, requires an id to match sql, and Mapper interface A completely object-oriented language.

1) Create a SQLSessionFactory in xml and implement it to access the database;

(1) First create an entity class:

package song;

public class User {

	private String id;
	private String username;
	private String userpwd;
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", userpwd=" + userpwd + "]";
	}
}

The get and set methods are omitted here; of course, the corresponding table data must be created.

(2) Then create an interface of the dao layer to implement related business operations;

package dao;

import pojo.User;

public interface UserDao {

	public User getUserById(String id);
	
	public void insertUser(User user);
}

(3) Follow the idea, mybatis is interface-oriented development, and there is no implementation class, so let's create a mapping between entity classes and databases, that is, mappers

<?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="dao.UserDao">
	<select id="getUserById" parameterType="string" resultType="pojo.User">
		select id,username,userpwd from t_users where id=#{id}
	</select>
	<insert id="insertUser" parameterType="pojo.User">
		insert into t_users(id,username,userpwd) values (#{id},#{username},#{userpwd})
	</insert>
</mapper>

At this point, our mapper has been created, but it should be noted that the namespace refers to the interface path, do not fill in the path of the entity class; with these, we need to create the basic xml of mybatis;

(3) Create a mybatis-config.xml 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>
	<!-- Database Environment-->
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC"></transactionManager>
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver"/>
				<property name="url" value="jdbc:mysql://localhost:3306/pom"/>
				<property name="username" value="root"/>
				<property name="password" value="mysql"/>
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="mapper/UserMapper.xml"/>
	</mappers>
</configuration>

Pay attention here, don't forget to register the mapper, POOLED means that the data source uses the concept of "pool" to organize JDBC and Connection objects; more instructions can be found on Baidu;

(4) At this point, it can be said that everything is ready; we just need the SQLSessionFactory we need, with it we will have the SQLSession, and then we will have everything;

package mybatis;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class CreatFactoryUtils {
	private static SqlSessionFactory sqlSessionFactory=null;
	private CreatFactoryUtils(){}
	public static SqlSessionFactory getSqlSessionFactory(){
			String resource="mybatis-config.xml";//This is our basic configuration file
			InputStream inputStream;
			if (sqlSessionFactory!=null) {
				return sqlSessionFactory;
			}
			try {
				inputStream=Resources.getResourceAsStream(resource);//Read the configuration file to generate a stream
				sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
			} catch (Exception e) {
				e.printStackTrace ();
				return null;
			}
			return sqlSessionFactory;
		}
	public static SqlSession openSqlSession(){
		if (sqlSessionFactory==null) {
			getSqlSessionFactory();
		}
		return sqlSessionFactory.openSession(true);
	}
}

Describe it here: There are two main points to explain; the first point is: new SqlSessionFactoryBuilder().build(inputStream); here is the SQLSessionFactory generated by the constructor through the creator mode, and the passed parameter is an InputStream type Parameters; there are many other conditions on the source code; you can download it by yourself; the second point is also the most important one: sqlSessionFactory.openSession(true); Why is this sentence important? Because if the true here is not added, there will be no new data in the database after the insert statement is executed. When it comes to this, you should know that, adding true is equivalent to setting the automatic commit transaction; not setting it is the default of mybatis; but it defaults to Transactions are not committed. So pay attention;

At this point, everything is over, the only thing I think about is to verify whether what we created works or not?

	public static void main(String[] args) {
		Logger log = Logger.getLogger(Test.class);
		User user=new User();
		user.setId("2");
		user.setUsername("hanjunyi");
		user.setUserpwd("12345");
		SqlSession sqlSession=null;
		try {
			sqlSession = CreatFactoryUtils.openSqlSession();
			UserDao mapper=sqlSession.getMapper(UserDao.class);
			User userById = mapper.getUserById("1");
			mapper.insertUser(user);
			log.info("================"+userById);
		} catch (Exception e) {
		}finally {
			if (sqlSession!=null) {
				sqlSession.close();
			}
		}
	}

Here is the table of the database:


There is only one data in the database, let's add one and query one to see the result:

Let's do it:


The execution steps we want are all executed; is there any new data in the only database left?


The result was what we wanted; the validation succeeded!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325592298&siteId=291194637