Tutorial for installing and configuring MyBatis in the Java+Spring+MySql environment

  • 2020-05-07 19:50:14
  • OfStack

1.MyBatis profile with configuration MyBatis+Spring+MySql

MyBatis profile 1.1
          MyBatis is a persistence layer framework for customizing SQL, stored procedures, and advanced mappings. MyBatis removes most of the JDBC code, sets parameters manually, and retrieves result sets. 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 required: 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.2MyBatis+Spring+MySql simple configuration
1.2.1 build Spring environment
(1) establish web project of maven;
(2) add Spring framework and configuration files;
(3) add the required jar package (spring framework, mybatis, mybatis-spring, junit, etc.) to pom.xml;
(4) change the configuration files for web.xml and spring;
(5) add one jsp page and the corresponding Controller;
(6) testing.
Reference: http: / / limingnihao iteye. com/blog / 830409. Build the SpringMVC project using Maven of Eclipse

1.2.2 establish MySql database
establishes a student course management database.
Schedule: student schedule, class schedule, teacher schedule, class schedule, student selection schedule.
Logical relation: each student has 1 class; Each class corresponds to one head teacher; Each teacher can only be the head teacher of one class;
Use the following sql to build the database, first set up the students table, insert data (more than 2).
For more sql please download the project source in resource/sql.


/*  Building 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 for the connection 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
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 the data access interface
Student class corresponding dao interface: 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

Student class sql statement file StudentMapper.xml
resultMap tag: mapping of table fields to properties.
Select label: 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 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 the mapper configuration file for MyBatis
creates the MyBatis configuration file in src/main/resource: mybatis-config.xml.
typeAliases tag: give a 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>  

1.2.3.5 modify the configuration file for Spring
is mainly bean: SqlSessionFactoryBean, in the mybatis.spring package. You need to specify the configuration file location and dataSource.
And data access interface corresponding to the implementation of bean. Created with MapperFactoryBean. The full name of the interface class and the reference to SqlSession factory bean need to be executed.


<!--  Import the properties configuration file  --> 
<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 not define mapper bean, using annotations:
Annotate StudentMapper


@Repository 
@Transactional 
public interface StudentMapper { 
} 

The corresponding need is to add scan in dispatcher-servlet. 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.2.4 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 = studentMapper.getStudent("10000013"); 
    System.out.println("name : " + entity.getStudentName()); 
  }   
} 

Test with Junit:


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

2. Master configuration file for MyBatis
needs to specify MyBatis master profile when defining sqlSessionFactory:


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

MyBatis configuration file large label configuration subtags include:


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

2.1 properties attribute

      properties is related to java's.properties configuration file. Configure resource for properties to specify the path to.properties, and then configure property for name and value under the properties tag to replace the corresponding property values in the.properties file.


  <!--  Attribute to replace  --> 
<properties resource="mysql.properties"> 
  <property name="jdbc.driverClassName" value="com.mysql.jdbc.Driver"/> 
  <property name="jdbc.url" value="jdbc:mysql://localhost:3306/student_manager"/> 
  <property name="username" value="root"/> 
  <property name="password" value="limingnihao"/> 
</properties> 

 
2.2 settings Settings
this is an important step in modifying the details of how MyBatis operates. The table below describes these Settings, their meanings, and default values.

设置项

描述

允许值

默认值

cacheEnabled

对在此配置文件下的所有cache 进行全局性开/关设置。

true | false

true

lazyLoadingEnabled

全局性设置懒加载。如果设为‘false',则所有相关联的都会被初始化加载。

true | false

true

aggressiveLazyLoading

当设置为‘true'的时候,懒加载的对象可能被任何懒属性全部加载。否则,每个属性都按需加载。

true | false

true

multipleResultSetsEnabled

允许和不允许单条语句返回多个数据集(取决于驱动需求)

true | false

true

useColumnLabel

使用列标签代替列名称。不同的驱动器有不同的作法。参考1下驱动器文档,或者用这两个不同的选项进行测试1下。

true | false

true

useGeneratedKeys

允许JDBC 生成主键。需要驱动器支持。如果设为了true,这个设置将强制使用被生成的主键,有1些驱动器不兼容不过仍然可以执行。

true | false

false

autoMappingBehavior

指定MyBatis 是否并且如何来自动映射数据表字段与对象的属性。PARTIAL将只自动映射简单的,没有嵌套的结果。FULL 将自动映射所有复杂的结果。

NONE,

PARTIAL,

FULL

PARTIAL

defaultExecutorType

配置和设定执行器,SIMPLE 执行器执行其它语句。REUSE 执行器可能重复使用prepared statements 语句,BATCH执行器可以重复执行语句和批量更新。

SIMPLE

REUSE

BATCH

SIMPLE

defaultStatementTimeout

设置1个时限,以决定让驱动器等待数据库回应的多长时间为超时

正整数

Not Set

(null)


Such as:


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

2.3 typeAliases type alias
The
type alias is short for Java type.
It is simply associated with the XML configuration, which is short for the verbose JAVA class name. Such as:


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

Use this configuration, "StudentEntity" can replace anywhere "com. manager. data. model. StudentEntity" is used.
For ordinary Java types, there are many built-in type aliases. They are case-insensitive, and because of overloaded names, note the special handling of native types.

别名

映射的类型

_byte

byte

_long

long

_short

short

_int

int

_integer

int

_double

double

_float

float

_boolean

boolean

string

String

byte

Byte

long

Long

short

Short

int

Integer

integer

Integer

double

Double

float

Float

boolean

Boolean

date

Date

decimal

BigDecimal

bigdecimal

BigDecimal

object

Object

map

Map

hashmap

HashMap

list

List

arraylist

ArrayList

collection

Collection

iterator

Iterator

2.4 typeHandlers type handle
whether MyBatis sets a parameter in a preprocessing statement or fetches a value from a result set, the type handler is used to convert the value obtained to the Java type in an appropriate manner. The following table describes the default type handler.

类型处理器

Java类型

JDBC类型

BooleanTypeHandler

Booleanboolean

任何兼容的布尔值

ByteTypeHandler

Bytebyte

任何兼容的数字或字节类型

ShortTypeHandler

Shortshort

任何兼容的数字或短整型

IntegerTypeHandler

Integerint

任何兼容的数字和整型

LongTypeHandler

Longlong

任何兼容的数字或长整型

FloatTypeHandler

Floatfloat

任何兼容的数字或单精度浮点型

DoubleTypeHandler

Doubledouble

任何兼容的数字或双精度浮点型

BigDecimalTypeHandler

BigDecimal

任何兼容的数字或10进制小数类型

StringTypeHandler

String

CHARVARCHAR类型

ClobTypeHandler

String

CLOBLONGVARCHAR类型

NStringTypeHandler

String

NVARCHARNCHAR类型

NClobTypeHandler

String

NCLOB类型

ByteArrayTypeHandler

byte[]

任何兼容的字节流类型

BlobTypeHandler

byte[]

BLOBLONGVARBINARY类型

DateTypeHandler

Datejava.util

TIMESTAMP类型

DateOnlyTypeHandler

Datejava.util

DATE类型

TimeOnlyTypeHandler

Datejava.util

TIME类型

SqlTimestampTypeHandler

Timestampjava.sql

TIMESTAMP类型

SqlDateTypeHandler

Datejava.sql

DATE类型

SqlTimeTypeHandler

Timejava.sql

TIME类型

ObjectTypeHandler

Any

其他或未指定类型

EnumTypeHandler

Enumeration类型

VARCHAR-任何兼容的字符串类型,作为代码存储(而不是索引)。


 
You can override the type handler or create your own type handler to handle unsupported or non-standard types. To do this, simply implement the TypeHandler interface (org.mybatis.type), and then map the new type handler class to the Java type, with an optional 1 JDBC type. Then add this type of processor to typeHandlers.
The newly defined type handler will override the existing type handler that handles String type attributes for Java and VARCHAR parameters and results. Note that MyBatis does not look at the database metadata to determine which type to use, so you must specify in the parameter and result mappings that the fields are of type VARCHAR to bind to the correct type handler. This is due to the fact that MyBatis does not know the data type until the statement is executed.


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

Add the typeHandler tag to the typeHandlers configuration file.


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

Related articles: