Introduction to MyBatis and how to configure MyBatis+Spring+MySql

  • 2020-06-23 00:27:07
  • OfStack

1.1 MyBatis profile

MyBatis is a persistence layer framework that allows you to customize SQL, stored procedures, and high-level mappings. MyBatis does away with most of the JDBC code, manual setting of parameters, and result set retrieval. MyBatis USES only simple XML and annotations to configure and map basic data types, Map interfaces, and POJO to database records. Mybatis is a "semi-automated" ORM implementation compared to "one-station" ORM solutions such as Hibernate and Apache OJB.

Jar package to use: mybatis-3.0.2.jar (mybatis core package). mybatis-spring-1.0.0.jar (combined with Spring package).
Download Address:

http://ibatis.apache.org/tools/ibator
http://code.google.com/p/mybatis/

1.2 Simple configuration of MyBatis+Spring+MySql

1.2.1 Build Spring environment

1. Establish web project of maven;

2. Add Spring framework and configuration file;

3. Add jar packages (spring framework, mybatis, ES57en-ES58en, junit, etc.) in ES52en. xml;

4. Change the configuration files of ES62en.xml and spring;

5. Add 1 jsp page and corresponding Controller;

6, test.

Reference: http: / / limingnihao iteye. com/blog / 830409. Use Maven of Eclipse to build the SpringMVC project

1.2.2 Establish MySql database

Set up a database of student course selection management.

Table: Student table, class table, teacher table, class schedule, student selection table.

Logical relation: each student has 1 class; Each class corresponds to a head teacher; Each teacher can only be a class teacher;

Use sql below to build the database. First create the student table and insert data (more than 2 pieces).

For more sql, please download the project source file in resource/sql.


/*  Build a database  */ 
CREATE DATABASE STUDENT_MANAGER; 
USE STUDENT_MANAGER; 
/*****  To establish student table  *****/ 
CREATE TABLE STUDENT_TBL 
( 
 STUDENT_ID   VARCHAR(255) PRIMARY KEY, 
 STUDENT_NAME  VARCHAR(10) NOT NULL, 
 STUDENT_SEX  VARCHAR(10), 
 STUDENT_BIRTHDAY DATE, 
 CLASS_ID   VARCHAR(255) 
); 
/* Insert student data */ 
INSERT INTO STUDENT_TBL (STUDENT_ID, 
       STUDENT_NAME, 
       STUDENT_SEX, 
       STUDENT_BIRTHDAY, 
       CLASS_ID) 
 VALUES (123456, 
   ' XXX ', 
   ' female ', 
   '1980-08-01', 
   121546 
   ) 

Create the configuration file mysql. properties to connect to MySql.


jdbc.driverClassName=com.mysql.jdbc.Driver 
jdbc.url=jdbc:mysql://localhost:3306/student_manager?user=root&password=limingnihao&useUnicode=true&characterEncoding=UTF-8

1.2.3 Build MyBatis environment

The order is arbitrary. The current order is because you can modify the written file as little as possible.

1.2.3.1 Create entity class: StudentEntity


public class StudentEntity implements Serializable { 
 private static final long serialVersionUID = 3096154202413606831L; 
 private ClassEntity classEntity; 
 private Date studentBirthday; 
 private String studentID; 
 private String studentName; 
 private String studentSex; 
 public ClassEntity getClassEntity() { 
  return classEntity; 
 } 
 public Date getStudentBirthday() { 
  return studentBirthday; 
 } 
 public String getStudentID() { 
  return studentID; 
 } 
 public String getStudentName() { 
  return studentName; 
 } 
 public String getStudentSex() { 
  return studentSex; 
 } 
 public void setClassEntity(ClassEntity classEntity) { 
  this.classEntity = classEntity; 
 } 
 public void setStudentBirthday(Date studentBirthday) { 
  this.studentBirthday = studentBirthday; 
 } 
 public void setStudentID(String studentID) { 
  this.studentID = studentID; 
 } 
 public void setStudentName(String studentName) { 
  this.studentName = studentName; 
 } 
 public void setStudentSex(String studentSex) { 
  this.studentSex = studentSex; 
 } 
} 

1.2.3.2 Create data access interface

The dao interface for the Student class: StudentMapper.


public interface StudentMapper { 
 public StudentEntity getStudent(String studentID); 
 public StudentEntity getStudentAndClass(String studentID); 
 public List<StudentEntity> getStudentAll(); 
 public void insertStudent(StudentEntity entity); 
 public void deleteStudent(StudentEntity entity); 
 public void updateStudent(StudentEntity entity); 
} 

1.2.3.3 Create SQL mapping statement file

sql statement file for Student class ES132en.xml

resultMap tag: Mapping of table fields to properties.

Select tag: Query sql.


<?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.manager.data.StudentMapper"> 
 <resultMap type="StudentEntity" id="studentResultMap"> 
  <id property="studentID" column="STUDENT_ID"/> 
  <result property="studentName" column="STUDENT_NAME"/> 
  <result property="studentSex" column="STUDENT_SEX"/> 
  <result property="studentBirthday" column="STUDENT_BIRTHDAY"/> 
 </resultMap> 
 <!--  Query the students according to id --> 
 <select id="getStudent" parameterType="String" resultType="StudentEntity" resultMap="studentResultMap"> 
  <![CDATA[ 
   SELECT * from STUDENT_TBL ST 
    WHERE ST.STUDENT_ID = #{studentID} 
  ]]> 
 </select> 
 <!--  Query student list  --> 
 <select id="getStudentAll" resultType="com.manager.data.model.StudentEntity" resultMap="studentResultMap"> 
  <![CDATA[ 
   SELECT * from STUDENT_TBL 
  ]]> 
 </select> 
</mapper> 

1.2.3.4 Create mapper configuration file for MyBatis

Create the MyBatis profile in src/main/resource: mybatis-ES153en.xml.

typeAliases tag: Give the class a name. com. manager. data. model. StudentEntity class, you can use StudentEntity instead.

Mappers tag: Loads the SQL mapping statement file for the entity class in MyBatis.


<?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="StudentEntity" type="com.manager.data.model.StudentEntity"/> 
 </typeAliases> 
 <mappers> 
  <mapper resource="com/manager/data/maps/StudentMapper.xml" />
 </mappers> 
</configuration> 

1.2.3.5 Modify the configuration file of Spring

bean: SqlSessionFactoryBean, (in the package of ES179en.spring). You need to specify the configuration file location and dataSource.

Implementation bean corresponding to the data access interface. Created with MapperFactoryBean. You need to perform the full name of the interface class and a reference to SqlSession factory bean.


<!--  Import the properties profile  --> 
<context:property-placeholder location="classpath:mysql.properties" /> 
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
 <property name="driverClassName" value="${jdbc.driverClassName}" /> 
 <property name="url" value="${jdbc.url}" /> 
</bean> 
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
 <property name="dataSource" ref="dataSource" /> 
</bean> 
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 
 <property name="configLocation" value="classpath:mybatis-config.xml" /> 
 <property name="dataSource" ref="dataSource" /> 
</bean> 
<! -  mapper bean --> 
<bean id="studentMapper" class="org.mybatis.spring.MapperFactoryBean"> 
 <property name="mapperInterface" value="com.manager.data.StudentMapper" /> 
 <property name="sqlSessionFactory" ref="sqlSessionFactory" /> 
</bean> 

You can also define bean without defining mapper, using annotations:

Annotate StudentMapper


@Repository 
@Transactional 
public interface StudentMapper { 
} 

Corresponding scanning should be added in ES201en-ES202en. xml:


<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 
 <property name="annotationClass" value="org.springframework.stereotype.Repository"/> 
 <property name="basePackage" value="com.liming.manager"/> 
 <property name="sqlSessionFactory" ref="sqlSessionFactory"/> 
</bean> 

1. Test StudentMapper

Use SpringMVC to test, create 1 TestController, configure tomcat, visit index.do page to test:


@Controller 
public class TestController { 
 @Autowired 
 private StudentMapper studentMapper; 
 @RequestMapping(value = "index.do") 
 public void indexPage() {  
  StudentEntity entity = studentMapper.getStudent("10000013"); 
  System.out.println("name : " + entity.getStudentName()); 
 }  
} 

Test with Junit:

Junit test:

Java code


jdbc.driverClassName=com.mysql.jdbc.Driver 
jdbc.url=jdbc:mysql://localhost:3306/student_manager?user=root&password=limingnihao&useUnicode=true&characterEncoding=UTF-8
0

Related articles: