1. Introduction and configuration of MyBatis+Spring+MySql
1.1 Introduction to MyBatis
MyBatis is a persistence layer framework that can customize SQL, stored procedures, and advanced mappings. MyBatis eliminates most of 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 POJOs to database records. Compared with "one-stop" ORM solutions such as Hibernate and Apache OJB, Mybatis is a "semi-automated" ORM implementation.
The Jar package that needs to be used: mybatis-3.0.2.jar (mybatis core package). mybatis-spring-1.0.0.jar (combined with Spring).
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 a maven web project;
(2) Add Spring framework and configuration files;
(3) Add the required jar packages (spring framework, mybatis, mybatis-spring, junit, etc.) to pom.xml;
(4) Change the configuration files of web.xml and spring;
(5) Add a jsp page and the corresponding controller;
(6) Test.
For reference: http://limingnihao.iteye.com/blog/830409. Build SpringMVC Project with Maven from Eclipse
1.2.2 Establishing MySql database
Establish a student course selection management database.
Table: Student table, class table, teacher table, course table, student course table.
Logical relationship: Each student has a class; each class corresponds to a class teacher; each teacher can only be the class teacher of one class;
Use the following SQL to build a database, first create a student table, and insert data (more than 2 items).
For more SQL, please download the project source file in resource/sql.
/* Create a database*/ CREATE DATABASE STUDENT_MANAGER; USE STUDENT_MANAGER; /***** Create 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 used 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 casual, and the current order is because you can modify the written files 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 a data access interface
The corresponding dao interface of 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
Student class sql statement file StudentMapper.xml
resultMap tag: Mapping of table fields and attributes.
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 student, 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 the 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 MyBatis mapper configuration file
Create MyBatis configuration file in src/main/resource: mybatis-config.xml.
typeAliases tag: Give alias the class an alias. The com.manager.data.model.StudentEntity class can be used instead of StudentEntity.
Mappers tag: Load SQL mapping statement file of 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 Spring's configuration file
It mainly adds the bean of the production factory class of SqlSession: SqlSessionFactoryBean (in mybatis.spring package). Requires specifying the configuration file location and dataSource.
Implementation bean corresponding to the data access interface. Created through MapperFactoryBean. It is necessary to execute the full name of the interface class and the reference to the SqlSession factory bean.
<!-- Import property configuration file--> <context:property-placeholder location="classpath:mysql.properties" /> <bean id="dataSource"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> </bean> <bean id="transactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <bean id="sqlSessionFactory"> <property name="configLocation" value="classpath:mybatis-config.xml" /> <property name="dataSource" ref="dataSource" /> </bean> <!― mapper bean --> <bean id="studentMapper"> <property name="mapperInterface" value="com.manager.data.StudentMapper" /> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean> You can also not define the mapper bean, use annotations:
Add StudentMapper to annotation
@Repository @Transactional public interface StudentMapper { }The corresponding needs are to add scans in dispatcher-servlet.xml:
<bean> <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 tests to create a TestController, configure tomcat, and access the index.do page for testing:
@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:
@RunWith(value = SpringJUnit4ClassRunner.class) @ContextConfiguration(value = "test-servlet.xml") public class StudentMapperTest { @Autowired private ClassMapper classMapper; @Autowired private StudentMapper studentMapper; @Transactional public void getStudentTest(){ StudentEntity entity = studentMapper.getStudent("10000013"); System.out.println("" + entity.getStudentID() + entity.getStudentName()); List<StudentEntity> studentList = studentMapper.getStudentAll(); for( StudentEntity entityTemp: studentList){ System.out.println(entityTemp.getStudentName()); } } } 2.MyBatis' main configuration file
When defining sqlSessionFactory, you need to specify the MyBatis main configuration file:
<bean id="sqlSessionFactory"> <property name="configLocation" value="classpath:mybatis-config.xml" /> <property name="dataSource" ref="dataSource" /> </bean>
The sub-tags under configuration in MyBatis configuration include:
configuration|-- properties|-- settings|--- typeAliases|--- typeHandlers|--- objectFactory|--- plugins|--- environments|--- environment|--- |---- |--- transactionManager|---- |---- |__ dataSource|__ mappers
2.1 properties properties
Properties configuration files are related to Java.properties. Configure the resource of properties to specify the path of .properties, and then configure the name and value of property under the properties tag. You can replace the corresponding property value in the .properties file.
<!-- Property Replacement--> <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
This is an important step for MyBatis to modify the operation process details. The following table describes these settings, meanings, and default values.
Settings | describe | Allowed values | default value |
cacheEnabled | All caches under this configuration file are globally on/off settings. | true | false | true |
lazyLoadingEnabled | Global settings lazy loading. If set to 'false', all associated ones will be initialized and loaded. | true | false | true |
aggressiveLazyLoading | When set to 'true', lazy loading objects may be loaded by all lazy properties. Otherwise, each property is loaded as needed. | true | false | true |
multipleResultSetsEnabled | Allow and do not allow a single statement to return multiple datasets (depending on driver requirements) | true | false | true |
useColumnLabel | Use column labels instead of column names. Different drives have different approaches. Refer to the drive documentation or test it out with these two different options. | true | false | true |
useGeneratedKeys | Allows JDBC to generate primary keys. Drive support is required. If set to true, this setting will force the generated primary key, some drives are incompatible but can still be executed. | true | false | false |
autoMappingBehavior | Specifies whether and how MyBatis automatically maps data table fields to objects' properties. PARTIAL will only automatically map simple, without nested results. FULL will automatically map all complex results. | NONE, PARTIAL, FULL | PARTIAL |
defaultExecutorType | Configure and set the executor, and the SIMPLE executor executes other statements. The REUSE executor may reuse the prepared statements statements statements, and the BATCH executor may repetitively execute statements and batch updates. | SIMPLE REUSE BATCH | SIMPLE |
defaultStatementTimeout | Set a time limit to determine how long the drive will wait for the database to respond to a timeout | Positive integer | Not Set (null) |
<settings> <setting name="cacheEnabled" value="true" /> <setting name="lazyLoadingEnabled" value="true" /> <setting name="multipleResultSetsEnabled" value="true" /> <setting name="useColumnLabel" value="true" /> <setting name="useGeneratedKeys" value="false" /> <setting name="enhancementEnabled" value="false" /> </settings>
2.3 typeAliases type alias
Type alias is the abbreviation of Java types.
It is simply associated with XML configuration, abbreviated as a lengthy JAVA class name. For example:
<typeAlias> <typeAlias alias="UserEntity" type="com.manager.data.model.UserEntity" /> <typeAlias alias="StudentEntity" type="com.manager.data.model.StudentEntity" /> <typeAlias alias="ClassEntity" type="com.manager.data.model.ClassEntity" /> </typeAlias>
With this configuration, "StudentEntity" can be used anywhere instead of "com.manager.data.model.StudentEntity".
For normal Java types, there are many built-in type alias. They are both case-insensitive, and due to overloaded names, you should pay attention to special handling of native types.
Alias | The type of map |
_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 takes a value from the result set, the type processor is used to convert the obtained value into Java type in the appropriate way. The following table describes the default type processor.
Type Processor | Java Types | JDBC Type |
BooleanTypeHandler | Boolean, boolean | Any compatible boolean value |
ByteTypeHandler | Byte, byte | Any compatible number or byte type |
ShortTypeHandler | Short, short | Any compatible digital or short form |
IntegerTypeHandler | Integer, int | Any compatible digital and integer |
LongTypeHandler | Long, long | Any compatible digital or long model |
FloatTypeHandler | Float, float | Any compatible digital or single-precision floating point type |
DoubleTypeHandler | Double, double | Any compatible digital or double precision floating point type |
BigDecimalTypeHandler | BigDecimal | Any compatible numeric or decimal decimal type |
StringTypeHandler | String | CHAR and VARCHAR types |
ClobTypeHandler | String | CLOB and LONGVARCHAR types |
NStringTypeHandler | String | NVARCHAR and NCHAR types |
NClobTypeHandler | String | NCLOB type |
ByteArrayTypeHandler | byte[] | Any compatible byte stream type |
BlobTypeHandler | byte[] | BLOB and LONGVARBINARY types |
DateTypeHandler | Date(java.util) | TIMESTAMP type |
DateOnlyTypeHandler | Date(java.util) | DATE type |
TimeOnlyTypeHandler | Date(java.util) | TIME Type |
SqlTimestampTypeHandler | Timestamp (java.sql) | TIMESTAMP type |
SqlDateTypeHandler | Date (java.sql) | DATE type |
SqlTimeTypeHandler | Time (java.sql) | TIME Type |
ObjectTypeHandler | Any | Other or unspecified type |
EnumTypeHandler | Enumeration type | VARCHAR - Any compatible string type, stored as code (not indexed). |
public class LimingStringTypeHandler implements TypeHandler { @Override public void setParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException { System.out.println("setParameter - parameter: " + ((String) parameter) + ", jdbcType: " + jdbcType.TYPE_CODE); ps.setString(i, ((String) parameter)); } @Override public Object getResult(ResultSet rs, String columnName) throws SQLException { System.out.println("getResult - columnName: " + columnName); return rs.getString(columnName); } @Override public Object getResult(CallableStatement cs, int columnIndex) throws SQLException { System.out.println("getResult - columnIndex: " + columnIndex); return cs.getString(columnIndex); } }Add the typeHandler tag in the typeHandlers in the configuration file.
<typeHandlers> <typeHandler javaType="String" jdbcType="VARCHAR" handler="liming.student.manager.type.LimingStringTypeHandler"/> </typeHandlers>
2.5 ObjectFactory object factory
Every time MyBatis creates a new instance of the result object, ObjectFactory is used. The default ObjectFactory is no different from creating an instance using the constructor of the target class. If there are already mapped parameters, it is also possible to use a constructor with parameters.
If you rewrite the default operation of ObjectFactory, you can create your own by inheriting org.apache.ibatis.reflection.factory.DefaultObjectFactory.
The ObjectFactory interface is simple. It contains two methods for creation, one is to deal with the default constructor, and the other is to deal with the parameter constructor. Ultimately, the setProperties method can be used to configure the ObjectFactory. After initializing your ObjectFactory instance, the properties defined in the objectFactory element body will be passed to the setProperties method.
public class LimingObjectFactory extends DefaultObjectFactory { private static final long serialVersionUID = -399284318168302833L; @Override public Object create(Class type) { return super.create(type); } @Override public Object create(Class type, List<Class> constructorArgTypes, List<Object> constructorArgs) { System.out.println("create - type: " + type.toString()); return super.create(type, constructorArgTypes, constructorArgs); } @Override public void setProperties(Properties properties) { System.out.println("setProperties - properties: " + properties.toString() + ", someProperty: " + properties.getProperty("someProperty")); super.setProperties(properties); } }Add objectFactory tag to the configuration file
<objectFactory type="liming.student.manager.configuration.LimingObjectFactory"> <property name="someProperty" value="100"/> </objectFactory>
2.6 plugins plugin
MyBatis allows you to intercept calls executed by mapped statements at a certain point. By default, MyBatis allows plugins to intercept method calls:
Details of methods in these classes can be found by looking at the signature of each method, and their source code is available in the MyBatis distribution package. You should understand the behavior of your overriding methods, assuming you are doing more than monitoring calls. If you try to modify or override a given method, you may break the core of MyBatis. This is a low-level class and method, and you should use plugins with caution.
Using plugins is the very simple power they provide. Simple implementation of the interceptor interface, and determine the specified signature you want to intercept.
2.7 environments
MyBatis can be configured with multiple environments. This can help you to map SQL to correspond to multiple databases, etc.
2.8 mapper mapper
Here is a statement that tells MyBatis where to look for SQL mapping. You can use the resource reference in the classpath, or use characters to enter the exact URL reference.
For example:
<mapper resource="com/manager/data/maps/UserMapper.xml" /> <mapper resource="com/manager/data/maps/StudentMapper.xml" /> <mapper resource="com/manager/data/maps/ClassMapper.xml" /> </mappers>