Use MyBatis alone to manage things
I have written related content in MyBatis's article. Here I will continue to write the simplest demo. Let's review the content of MyBatis before. First, create a table and create 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 + "]}";}} To put it more, overriding the toString() method for entity classes and printing each (or a key attribute) is a recommended approach. Next is config.xml, which contains the basic jdbc configuration:
<?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 there is 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 a MyBatisUtil.java, which is used to create some basic MyBatis elements. The subsequent classes inherit this class:
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-level development requirements:
1. Separate definition and implementation
2. Layered development, usually Dao-->Service-->Controller, it is not ruled out that one more layer/several layer or one less layer is added according to the specific situation.
So, first write a StudentDao.java interface:
public interface StudentDao{public List<Student> selectAllStudents();public int insertStudent(Student student);} Finally, write a StudentDaoImpl.java to implement this interface. Note that you must 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));}} The result must be empty.
I have said this example is both a review and an introduction to our content today. The reason for this is empty is that the insert operation has been done, but MyBatis will not help us submit things automatically, so what is displayed is naturally empty. In this case, you must manually submit the transaction through the commit() method of SqlSession, that is, open the comment on line 17 of the StudentDaoImpl.java class.
To put it more, in addition to the basic MyBatis insertion operation, this example also has the function of returning the inserted primary key id on the basis of insertion.
Next, use Spring to manage MyBatis things, which is also the most commonly used thing management practice in enterprise-level development.
Manage MyBatis things with Spring
There are many articles on the Internet to explain this, and I have searched a lot, but either copy and paste each other or not explain the entire example clearly. Through this part, I try to explain how to use Spring to manage MyBatis things.
Using Spring to manage MyBatis things, in addition to Spring's necessary module beans, context, core, expression, and commons-logging, the following content is also required:
(1) MyBatis-Spring-1.x.0.jar, this is a necessary jar package for Spring integration MyBatis.
(2) Database connection pool, dbcp and c3p0 can be used. I am using Alibaba's druid here
(3) jdbc, tx, aop, jdbc is basically not to mention. Tx and aop are used because Spring's support for MyBatis thing management is achieved through aop
(4) aopalliance.jar, this is a necessary jar package to use Spring AOP
The above jar package will be downloaded using Maven. Those who have not used Maven can download it on CSDN. You can search for it.
In the configuration file config.xml of MyBatis, the jdbc connection can be removed, and only the typeAliases part 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>
Let me mention that MyBatis another configuration file student_mapper.xml does not need to be changed. Next, write the Spring configuration file, and I name it 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.xsdhttp://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.xsdhttp://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 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, use alibaba's Druid --><bean id="dataSource" 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"><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"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
This mainly includes the transaction manager and the database connection pool.
In addition, we see that there is a SqlSessionFactory. Friends who have used MyBatis must be familiar with this class. It is used to configure the MyBatis environment. There are two attributes configLocation and mapperLocations in the SqlSessionFactory. As the name implies, it represents the location of the configuration file and the location of the mapping file. Here, as long as the path is configured correctly, Spring will automatically load these two configuration files.
Then what you want to modify is Dao's implementation class. At this time, you no longer inherit the previous MyBatisUtil class, but inherit the SqlSessionDaoSupport.java from MyBatis-Spring-1.x.0.jar. The specific code is as follows:
@Repositorypublic class StudentDaoImpl extends SqlSessionDaoSupport implements StudentDao{private static final String NAMESPACE = "StudentMapper.";@Resourcepublic void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory){super.setSqlSessionFactory(sqlSessionFactory);}public List<Student> selectAllStudents(){return getSqlSession().selectList(NAMESPACE + "selectAllStudents");}public int insertStudent(Student student){return getSqlSession().insert(NAMESPACE + "insertStudent", student);}}Two annotations are used here, let’s talk about them separately.
(1) @Repository, this annotation is the same as @Component, @Controller and our most common @Service annotations, which can all declare a class as a Spring bean. Their differences are not in specific semantics, but more in the positioning of the annotation. As mentioned before, enterprise-level applications focus on the concept of hierarchical development, so these four similar annotations should be understood as follows:
•@Repository annotation corresponds to the persistence layer, namely the Dao layer, which is used to directly interact with the database. Generally speaking, a method corresponds to a specific Sql statement
•@Service annotation, which corresponds to the service layer, is the Service layer, which is used to combine single/multiple Sql statements. Of course, if it is simple, you will directly call a method of the Dao layer.
•@Controller annotation, which corresponds to the control layer, that is, the control layer in the MVC design mode. Its function is to receive user requests, call different services to get data according to requests, and combine data according to requirements and wrap it back to the front end.
•@Component annotation, which corresponds more to the concept of a component. If a bean does not know that it belongs to a layer, you can use @Component annotation to annotate.
This also reflects one of the advantages of annotations: seeing the name and knowing the meaning, that is, seeing this annotation, you roughly know the function of this class, that is, its positioning in the entire project.
(2) @Resource, this annotation and @Autowired annotation have the same meaning, and both can be automatically injected with attribute attributes. Since SqlSessionFactory is the core of MyBatis, it has been declared in spring.xml. Therefore, the bean with the id "sqlSessionFactory" is injected here through the @Resource annotation. After that, the SqlSession can be obtained through the getSqlSession() method and the data is added, deleted, modified, and checked.
Finally, it's nothing more than writing a test class to test:
public class StudentTest{public static void main(String[] args){ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");StudentDao studentDao = (StudentDao)ac.getBean("studentDaoImpl");Student student = new Student();student.setStudentName("Lucy");int j = studentDao.insertStudent(student);System.out.println("j = " + j + "/n");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));}} Since 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 letter lowercase + remaining letters", that is, "studentDaoImpl".
After running the program, you can see that the new Student was traversed on the console, that is, the Student was directly inserted into the database. There was no commit or rollback in the whole process. All of them were implemented by Spring. This is to use Spring to manage things on MyBatis.
postscript
This article reviews the basic use of MyBatis and uses Spring to manage things on MyBatis, and gives more detailed code examples. Friends in need can study it according to the code. Based on this article, I will write an article later to explain the implementation of multi-data's thing management between single tables and multiple tables. This requirement is also a common requirement in enterprises and applications.