Introduction and Configuration of mybatis _ Power Node Java College Collation

  • 2020-09-28 08:53:19
  • OfStack

MyBatis profile

MyBatis is a persistence layer framework that allows you to customize SQL, stored procedures, and high-level mappings. MyBatis eliminates most of the JDBC code, manual parameter setting, 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/

MyBatis+Spring+MySql simple configuration

Build the Spring environment

1. Establish web project of maven;
2. Add Spring framework and configuration file;
3. Add jar packages (spring framework, mybatis, ES58en-ES59en, junit, etc.) in ES53en. xml;
4. Change the configuration files of ES62en.xml and spring;
5. Add 1 jsp page and corresponding Controller;
6, test.

Set up 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 1 head teacher; Each teacher can only be a class teacher;

Use the following sql to build the database. First, set up the student table and insert data (more than 2 pieces).

For more sql, 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=bjpowernode&useUnicode=true&characterEncoding=UTF-8 

Build the MyBatis environment

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

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; 
  } 
} 

Create a 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); 
} 

Create the SQL mapping statement file

The sql statement file for the Student class ES129en.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="commanagerdatamodelStudentEntity" resultMap="studentResultMap"> 
    <![CDATA[ 
      SELECT * from STUDENT_TBL 
    ]]>  
  </select> 
   
</mapper> 

Create the mapper configuration file for MyBatis

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

typeAliases tag: Give the class an individual 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> 

Modify the configuration file for Spring

Main is to add SqlSession to the production factory class of bean: SqlSessionFactoryBean, (in the mybatis. spring package). You need to specify the configuration file location and dataSource.

Implementation bean corresponding to the data access interface. Created with MapperFactoryBean. You need to execute 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 the annotation:

Annotate StudentMapper


@Repository 
@Transactional 
public interface StudentMapper { 
} 

Corresponding scanning should be added in dispatcher-ES206en. xml:


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

Test StudentMapper

Use SpringMVC 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 = studentMappergetStudent("10000013"); 
    System.out.println("name : " + entity.getStudentName()); 
  }   
} 

Using Junit test:


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


Related articles: