In MyBatis5 Spring integrates MyBatis business management

  • 2020-05-09 18:42:35
  • OfStack

Use MyBatis alone to manage things

The previous MyBatis article has written about the relevant content, here continue to write the most simple Demo, as a review of the content of MyBatis before 1, first set up a table, set up a simple Student table:


create table student
(
student_id int auto_increment,
student_name varchar(20) not null,
primary key(student_id)
)

Create entity class Student.java:


public class Student
{
private int studentId;
private String studentName;
public int getStudentId()
{
return studentId;
}
public void setStudentId(int studentId)
{
this.studentId = studentId;
}
public String getStudentName()
{
return studentName;
}
public void setStudentName(String studentName)
{
this.studentName = studentName;
}
public String toString()
{
return "Student{[studentId:" + studentId + "], [studentName:" + studentName + "]}";
}
} 

One more sentence, overriding the toString() method for the entity class, and printing each of them (or key attributes) is a recommended practice. Then config.xml. Inside is the basic configuration of jdbc:


<?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>
<typeAliases>
<typeAlias alias="Student" type="org.xrq.domain.Student" />
</typeAliases>
<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/test"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="student_mapper.xml"/>
</mappers>
</configuration> 

Then student_mapper.xml, mainly the specific sql statement:


<mapper namespace="StudentMapper">
<resultMap type="Student" id="StudentMap">
<id column="student_id" property="studentId" jdbcType="INTEGER" />
<result column="student_name" property="studentName" jdbcType="VARCHAR" />
</resultMap>
<select id="selectAllStudents" resultMap="StudentMap">
select student_id, student_name from student;
</select>
<insert id="insertStudent" useGeneratedKeys="true" keyProperty="studentId" parameterType="Student">
insert into student(student_id, student_name) values(#{studentId, jdbcType=INTEGER}, #{studentName, jdbcType=VARCHAR});
</insert>
</mapper> 

Create an MyBatisUtil.java to create an MyBatis base element, which all subsequent classes inherit:


public class MyBatisUtil
{
protected static SqlSessionFactory ssf;
protected static Reader reader;
static
{
try
{
reader = Resources.getResourceAsReader("config.xml");
ssf = new SqlSessionFactoryBuilder().build(reader);
} 
catch (IOException e)
{
e.printStackTrace();
}
}
protected SqlSession getSqlSession()
{
return ssf.openSession();
}
} 

Enterprise development:

1. Separate definition and implementation

2. Layered development, usually Dao-- > Service-- > Controller does not exclude the possibility of one more/more layers or one less layer depending on the situation

So, write 1 StudentDao.java interface:


public interface StudentDao
{
public List<Student> selectAllStudents();
public int insertStudent(Student student);
}

Finally, write 1 StudentDaoImpl.java to implement the interface. Be careful to inherit the MyBatisUtil.java class:


public class StudentDaoImpl extends MyBatisUtil implements StudentDao
{
private static final String NAMESPACE = "StudentMapper.";
public List<Student> selectAllStudents()
{
SqlSession ss = getSqlSession();
List<Student> list = ss.selectList(NAMESPACE + "selectAllStudents");
ss.close();
return list;
}
public int insertStudent(Student student)
{
SqlSession ss = getSqlSession();
int i = ss.insert(NAMESPACE + "insertStudent", student);
// ss.commit();
ss.close();
return i;
}
}

Write a test class:


public class StudentTest
{
public static void main(String[] args)
{
StudentDao studentDao = new StudentDaoImpl();
Student student = new Student();
student.setStudentName("Jack");
studentDao.insertStudent(student);
System.out.println(" The primary key inserted is: " + student.getStudentId());
System.out.println("-----Display students------");
List<Student> studentList = studentDao.selectAllStudents();
for (int i = 0, length = studentList.size(); i < length; i++)
System.out.println(studentList.get(i));
}
}

So 1 is definitely empty.

I said this example is both a review and a lead into what we're going to do today, and the reason it's empty is because the insert operation has been done, but MyBatis doesn't automatically submit things for us, so the display is empty. At this point the transaction must be manually committed through SqlSession's commit() method, which opens the comment on line 17 of the StudentDaoImpl.java class.

In addition to the basic MyBatis insert operation, this example has the ability to return the primary key id for insertion.

Next, use Spring to manage MyBatis things, which is the most common thing management practice in enterprise development.

Manage MyBatis things using Spring

There are a lot of articles on the web about this, and I've done a lot of searching, but they either copy and paste each other, or they don't make the whole example clear, and I'm trying to make it clear how to use Spring to manage MyBatis things through this part.

In addition to beans, context, core, expression, commons-logging necessary modules for Spring management, Spring requires the following:

(1) MyBatis-Spring-1. x.0.jar, which is the Spring package necessary to integrate MyBatis

(2) database connection pool, dbcp, c3p0 can be used, here I use the druid of ali

(3) jdbc, tx, aop, jdbc are basic. tx and aop are used because Spring supports MyBatis business management through aop

(4) aopalliance. jar, this is one jar package necessary to use Spring AOP

The above jar package will use Maven and can be downloaded using Maven. Those who have not used Maven can go to CSDN and download it.

In MyBatis's configuration file config. xml, the part about jdbc connection can be removed, and only the part of typeAliases can be retained:


<?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>
<typeAliases>
<typeAlias alias="Student" type="org.xrq.domain.Student" />
</typeAliases>
</configuration> 

MyBatis, student_mapper.xml, the other configuration file, student_mapper.xml, does not need to be changed. Next, write the Spring configuration file, which I'll call spring.xml:


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd 
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd 
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
<!--  Annotation configuration  -->
<tx:annotation-driven transaction-manager="transactionManager" />
<context:annotation-config /> 
<context:component-scan base-package="org.xrq" />
<!--  Database connection pool , Used here alibaba the Druid -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="jdbc:mysql://localhost:3306/test" /> 
<property name="username" value="root" /> 
<property name="password" value="root" /> 
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:config.xml" />
<property name="mapperLocations" value="classpath:*_mapper.xml" />
<property name="dataSource" ref="dataSource" />
</bean>
<!--  Transaction manager  --> 
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
<property name="dataSource" ref="dataSource" /> 
</bean> 
</beans> 

This is the transaction manager and the database connection pool.

And we see a SqlSessionFactory, used MyBatis friends 1 set is not unfamiliar to this class, it is used to configure MyBatis environment, SqlSessionFactory has two attributes configLocation, mapperLocations inside, just as its name implies, representing the location of the configuration file and the location of the mapping file, here as long as the path is configured correctly, Spring to automatically load the two configuration files.

Then, the implementation class of Dao needs to be modified. Now, instead of inheriting the previous MyBatisUtil class, MyBatis-Spring-1. x.0.jar inherits SqlSessionDaoSupport.java.


public class Student
{
private int studentId;
private String studentName;
public int getStudentId()
{
return studentId;
}
public void setStudentId(int studentId)
{
this.studentId = studentId;
}
public String getStudentName()
{
return studentName;
}
public void setStudentName(String studentName)
{
this.studentName = studentName;
}
public String toString()
{
return "Student{[studentId:" + studentId + "], [studentName:" + studentName + "]}";
}
} 
0

Two notes are used here, one for each.

(1) @Repository, this annotation and the @Component, @Controller and our most common @Service annotations are 1 function that can declare a class as an Bean of Spring. They differ not so much in the semantics as in the positioning of the annotations. As mentioned earlier, enterprise applications focus on the concept of layered development, so these four similar annotations should be understood as follows:

The & # 8226; The @Repository annotation corresponds to the persistence layer, or Dao layer, which interacts directly with the database. Typically, one method corresponds to one specific Sql statement
The & # 8226; The annotation @Service corresponds to the service layer, Service layer, which is used to combine single/multiple Sql statements. Of course, if it is simple, some method of Dao layer can be directly called
The & # 8226; Note @Controller, which corresponds to the control layer in MVC design mode. Its function is to receive user requests, call different Service to fetch data according to the request, and combine and wrap the data back to the front end according to the requirements
The & # 8226; The @Component annotation, which more closely corresponds to the concept of a component, can be annotated using the @Component annotation if an Bean does not know it belongs to a layer

This also illustrates one of the advantages of annotations: they give you a general idea of what the class does and how it fits into the overall project.

(2) @Resource. This annotation and the @Autowired annotation have the same meaning and can be automatically injected into the attribute. Since SqlSessionFactory is the core of MyBatis, it has been declared in spring.xml. Therefore, Bean, which is "sqlSessionFactory", is injected into id via the annotation @Resource, and then SqlSession can be obtained through getSqlSession() method and be added, deleted, modified and checked.

Finally, it is nothing more than to write a test class and test 1:


public class Student
{
private int studentId;
private String studentName;
public int getStudentId()
{
return studentId;
}
public void setStudentId(int studentId)
{
this.studentId = studentId;
}
public String getStudentName()
{
return studentName;
}
public void setStudentName(String studentName)
{
this.studentName = studentName;
}
public String toString()
{
return "Student{[studentId:" + studentId + "], [studentName:" + studentName + "]}";
}
} 
1

Because the StudentDaoImpl.java class USES the @Repository annotation and does not specify an alias, the name of StudentDaoImpl.java in the Spring container is "first lowercase + remaining letters", that is, "studentDaoImpl".

Run 1, you can see that Student from new is traversed on the console, that is, Student is directly inserted into the database. There is no commit or rollback in the whole process. All of them are realized by Spring, which is to use Spring to manage MyBatis.

Afterword.

This paper reviews the basic use of MyBatis and the management of MyBatis with Spring, and gives a more detailed code example. Those who need it can follow the code to study 1. On the basis of this paper, I will write another article to explain the implementation of multi-data management between single table and multi-table, which is also a common requirement in enterprises and applications.


Related articles: