catalogue
2: Import mybaits dependent package
5: Interface between code entity class and mapper/dao layer
SqlsessionFactoryBuilder class
1: Create maven project
Pre project preparation: create database
Mybati Chinese document: https://mybatis.org/mybatis-3/zh/getting-started.html
Click file
2: Import mybaits dependent package
<dependencies> <!--mybatis Core package--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <!--mysql Driver package--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <!-- Unit test generation test Method needs --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> </dependency> <!-- Logs are not required but necessary --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies>
3: Configure
Create mybaits config. In resource XML 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 Core profile--> <!--& amount to & Because it needs to be translated here, and the last part needs to modify the time zone and add serverTimezone=UTC--> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> </configuration>
4: Write mybaits tool class
This is the file directory structure created
mybaits tool class
To get the sqlsession factory, I encapsulated it into a method, which can also be added to the startup class and test class
//Get SqlSession from SqlSessionFactory public class MyBatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { //Using Mybatis, the first step is to obtain the sqlSessionFactory object String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } //Now that we have SqlSessionFactory, as the name suggests, we can get an instance of SqlSession from it. //SqlSession provides all the methods required to execute SQL commands in the database. // You can directly execute the mapped SQL statements through the SqlSession instance. public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
5: Interface between code entity class and mapper/dao layer
Entity class User;
public class User { private int id; private String name; private String pwd; //Parameterless Constructor public User() { } //With reference Constructor public User(int id, String name, String pwd) { this.id = id; this.name = name; this.pwd = pwd; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } //toString @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", pwd='" + pwd + '\'' + '}'; } }
mapper layer:
public interface UserMapper { public interface UserDao { List<User> getUserList(); } }
Mapper configuration file for implementing mapper layer interface:
<?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="one.mapper.UserMapper"> <select id="getUserList" resultType="one.domain.User"> select * from user; </select> </mapper>
6: Test
Right click goto in the mapper layer of the interface you want to test
public class UserDaoTest { @Test public void test(){ //Step 1: get sqlSession object SqlSession sqlSession = MyBatisUtils.getSqlSession(); //Method 1: getMapper UserDao userDao = sqlSession.getMapper(UserDao.class); List<User> userList = userDao.getUserList(); //userList.for shortcut for (User user : userList) { System.out.println(user); } //Close sqlSession sqlSession.close(); } }
7: Attention items
SqlsessionFactoryBuilder class
Its main function is to create sqlsessionfactory; The creation of sqlsessionfactory depends on the builder method of this class. After the factory is created, the mission of this class ends. Therefore, this class can be defined in a local method. The method ends and the object is destroyed
SqlSessionFactory interface
SqlSessionFactory is a class that creates sqlsession links. It is a thread safe class for system development. Therefore, the whole application can be created once without destruction and replacement; Use openSession() of an interface to create database links
SqlSession interface
It is used to establish a link with the database, and the thread is unsafe. It can be used and sold at any time;
The SqlSession interface object is used to perform persistence operations. A SqlSession corresponds to a database session, which starts with the creation of the SqlSession object and ends with the closing of the SqlSession object.
The SqlSession interface object is thread unsafe, so you need to call its close() method to close it immediately before the end of each database session. The session needs to be created again. When closing, it will judge whether the current SqlSession has been submitted: if it has not been submitted, it will be closed after rollback (the change operation must be submi to take effect); If it has been submitted, close SqlSession directly. Therefore, SqlSession does not need to be rolled back manually.