您的位置:首页 > 其它

MyBatis 总结记录

2016-07-06 15:29 239 查看

1.1MyBatis简介

MyBatis 是一个可以自定义SQL、存储过程和高级映射的持久层框架。MyBatis 摒除了大部分的JDBC代码、手工设置参数和结果集重获。MyBatis 只使用简单的XML 和注解来配置和映射基本数据类型、Map 接口和POJO 到数据库记录。相对Hibernate和Apache OJB等“一站式”ORM解决方案而言,Mybatis 是一种“半自动化”的ORM实现。
需要使用的Jar包:mybatis-3.0.2.jar(mybatis核心包)。mybatis-spring-1.0.0.jar(与Spring结合包)。

下载地址:
http://ibatis.apache.org/tools/ibator
http://code.google.com/p/mybatis/

1.2MyBatis+Spring+MySql简单配置

1.2.1搭建Spring环境

1,建立maven的web项目;
2,加入Spring框架、配置文件;
3,在pom.xml中加入所需要的jar包(spring框架的、mybatis、mybatis-spring、junit等);
4,更改web.xml和spring的配置文件;
5,添加一个jsp页面和对应的Controller;
6,测试。

可参照:http://limingnihao.iteye.com/blog/830409使用Eclipse的Maven构建SpringMVC项目

1.2.2建立MySql数据库

建立一个测试数据库。

使用下面的sql进行建数据库,先建立学生表,插入数据(2条以上)。

更多sql请下载项目源文件,在resource/sql中。

Sql代码

/* 建立数据库 */

CREATE DATABASE STUDENT_MANAGER;

USE STUDENT_MANAGER;

/***** 建立student表 *****/

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 INTO STUDENT_TBL (STUDENT_ID,

STUDENT_NAME,

STUDENT_SEX,

STUDENT_BIRTHDAY,

CLASS_ID)

VALUES (123456,

'某某某',

'女',

'1980-08-01',

121546

)

创建连接MySql使用的配置文件mysql.properties。

Mysql.properties代码


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搭建MyBatis环境

顺序随便,现在的顺序是因为可以尽量的少的修改写好的文件。

1.2.3.1创建实体类: StudentEntity

Java代码

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创建数据访问接口

Student类对应的dao接口:StudentMapper。

Java代码

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创建SQL映射语句文件

Student类的sql语句文件StudentMapper.xml
resultMap标签:表字段与属性的映射。
Select标签:查询sql。

Xml代码

<?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>

<!-- 查询学生,根据id -->

<select id="getStudent" parameterType="String" resultType="StudentEntity" resultMap="studentResultMap">

<![CDATA[

SELECT * from STUDENT_TBL ST

WHERE ST.STUDENT_ID = #{studentID}

]]>

</select>

<!-- 查询学生列表 -->

<select id="getStudentAll" resultType="com.manager.data.model.StudentEntity" resultMap="studentResultMap">

<![CDATA[

SELECT * from STUDENT_TBL

]]>

</select>

</mapper>

1.2.3.4创建MyBatis的mapper配置文件

在src/main/resource中创建MyBatis配置文件:mybatis-config.xml。
typeAliases标签:给类起一个别名。com.manager.data.model.StudentEntity类,可以使用StudentEntity代替。
Mappers标签:加载MyBatis中实体类的SQL映射语句文件。

Xml代码

<?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修改Spring 的配置文件

主要是添加SqlSession的制作工厂类的bean:SqlSessionFactoryBean,(在mybatis.spring包中)。需要指定配置文件位置和dataSource。
和数据访问接口对应的实现bean。通过MapperFactoryBean创建出来。需要执行接口类全称和SqlSession工厂bean的引用。

Xml代码

<!-- 导入属性配置文件 -->

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

也可以不定义mapper的bean,使用注解:

将StudentMapper加入注解

Java代码

@Repository

@Transactional

public interface StudentMapper {

}

对应的需要在dispatcher-servlet.xml中加入扫描:

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测试StudentMapper

使用SpringMVC测试,创建一个TestController,配置tomcat,访问index.do页面进行测试:

Java代码

@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());

}

}

使用Junit测试:

Java代码

使用Junit测试:

Java代码

@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());

}

}

}

SQL 映射XML 文件是所有sql语句放置的地方。需要定义一个workspace,一般定义为对应的接口类的路径。写好SQL语句映射文件后,需要在MyBAtis配置文件mappers标签中引用,例如:

Xml代码

<mappers>

<mapper resource="com/liming/manager/data/mappers/UserMapper.xml" />

<mapper resource="com/liming/manager/data/mappers/StudentMapper.xml" />

<mapper resource="com/liming/manager/data/mappers/ClassMapper.xml" />

<mapper resource="com/liming/manager/data/mappers/TeacherMapper.xml" />

</mappers>

当Java接口与XML文件在一个相对路径下时,可以不在myBatis配置文件的mappers中声明。

SQL 映射XML 文件一些初级的元素:

1. cache – 配置给定模式的缓存
2. cache-ref – 从别的模式中引用一个缓存
3. resultMap – 这是最复杂而却强大的一个元素了,它描述如何从结果集中加载对象
4. sql – 一个可以被其他语句复用的SQL 块
5. insert – 映射INSERT 语句
6. update – 映射UPDATE 语句
7. delete – 映射DELEETE 语句
8. select - 映射SELECT语句

2.1 resultMap

resultMap 是MyBatis 中最重要最强大的元素了。你可以让你比使用JDBC 调用结果集省掉90%的代码,也可以让你做许多JDBC 不支持的事。现实上,要写一个等同类似于交互的映射这样的复杂语句,可能要上千行的代码。ResultMaps 的目的,就是这样简单的语句而不需要多余的结果映射,更多复杂的语句,除了只要一些绝对必须的语句描述关系以外,再也不需要其它的。

resultMap属性:type为java实体类;id为此resultMap的标识。

resultMap可以设置的映射:

1. constructor – 用来将结果反射给一个实例化好的类的构造器

a) idArg – ID 参数;将结果集标记为ID,以方便全局调用
b) arg –反射到构造器的通常结果

2. id – ID 结果,将结果集标记为ID,以方便全局调用

3. result – 反射到JavaBean 属性的普通结果

4. association – 复杂类型的结合;多个结果合成的类型

a) nested result mappings – 几resultMap 自身嵌套关联,也可以引用到一个其它上

5. collection –复杂类型集合a collection of complex types

6. nested result mappings – resultMap 的集合,也可以引用到一个其它上

7. discriminator – 使用一个结果值以决定使用哪个resultMap

a) case – 基本一些值的结果映射的case 情形

i. nested result mappings –一个case 情形本身就是一个结果映射,因此也可以包括一些相同的元素,也可以引用一个外部resultMap。

2.1.1 id、result

id、result是最简单的映射,id为主键映射;result其他基本数据库表字段到实体类属性的映射。
最简单的例子:

Xml代码

<resultMap type="liming.student.manager.data.model.StudentEntity" id="studentResultMap">

<id property="studentId" column="STUDENT_ID" javaType="String" jdbcType="VARCHAR"/>

<result property="studentName" column="STUDENT_NAME" javaType="String" jdbcType="VARCHAR"/>

<result property="studentSex" column="STUDENT_SEX" javaType="int" jdbcType="INTEGER"/>

<result property="studentBirthday" column="STUDENT_BIRTHDAY" javaType="Date" jdbcType="DATE"/>

<result property="studentPhoto" column="STUDENT_PHOTO" javaType="byte[]" jdbcType="BLOB" typeHandler="org.apache.ibatis.type.BlobTypeHandler" />

</resultMap>

id、result语句属性配置细节:

属性

描述

property

需要映射到JavaBean 的属性名称。

column

数据表的列名或者标签别名。

javaType

一个完整的类名,或者是一个类型别名。如果你匹配的是一个JavaBean,那MyBatis 通常会自行检测到。然后,如果你是要映射到一个HashMap,那你需要指定javaType 要达到的目的。

jdbcType

数据表支持的类型列表。这个属性只在insert,update 或delete 的时候针对允许空的列有用。JDBC 需要这项,但MyBatis 不需要。如果你是直接针对JDBC 编码,且有允许空的列,而你要指定这项。

typeHandler

使用这个属性可以覆写类型处理器。这项值可以是一个完整的类名,也可以是一个类型别名。

支持的JDBC类型
为了将来的引用,MyBatis 支持下列JDBC 类型,通过JdbcType 枚举:
BIT,FLOAT,CHAR,TIMESTAMP,OTHER,UNDEFINED,TINYINT,REAL,VARCHAR,BINARY,BLOB,NVARCHAR,SMALLINT,DOUBLE,LONGVARCHAR,VARBINARY,CLOB,NCHAR,INTEGER,NUMERIC,DATE,LONGVARBINARY,BOOLEAN,NCLOB,BIGINT,DECIMAL,TIME,NULL,CURSOR

2.1.2 constructor

我们使用id、result时候,需要定义java实体类的属性映射到数据库表的字段上。这个时候是使用JavaBean实现的。当然我们也可以使用实体类的构造方法来实现值的映射,这个时候是通过构造方法参数的书写的顺序来进行赋值的。
使用construcotr功能有限(例如使用collection级联查询)。
上面使用id、result实现的功能就可以改为:

Xml代码

<resultMap type="StudentEntity" id="studentResultMap" >

<constructor>

<idArg javaType="String" column="STUDENT_ID"/>

<arg javaType="String" column="STUDENT_NAME"/>

<arg javaType="String" column="STUDENT_SEX"/>

<arg javaType="Date" column="STUDENT_BIRTHDAY"/>

</constructor>

</resultMap>

当然,我们需要定义StudentEntity实体类的构造方法:

Java代码

public StudentEntity(String studentID, String studentName, String studentSex, Date studentBirthday){

this.studentID = studentID;

this.studentName = studentName;

this.studentSex = studentSex;

this.studentBirthday = studentBirthday;

}

2.1.3 association联合

联合元素用来处理“一对一”的关系。需要指定映射的Java实体类的属性,属性的javaType(通常MyBatis 自己会识别)。对应的数据库表的列名称。如果想覆写的话返回结果的值,需要指定typeHandler。
不同情况需要告诉MyBatis 如何加载一个联合。MyBatis 可以用两种方式加载:

1. select: 执行一个其它映射的SQL 语句返回一个Java实体类型。较灵活;
2. resultsMap: 使用一个嵌套的结果映射来处理通过join查询结果集,映射成Java实体类型。

例如,一个班级对应一个班主任。
首先定义好班级中的班主任属性:

Java代码

private TeacherEntity teacherEntity;

2.1.3.1使用select实现联合

例:班级实体类中有班主任的属性,通过联合在得到一个班级实体时,同时映射出班主任实体。

这样可以直接复用在TeacherMapper.xml文件中定义好的查询teacher根据其ID的select语句。而且不需要修改写好的SQL语句,只需要直接修改resultMap即可。

ClassMapper.xml文件部分内容:

Xml代码

<resultMap type="ClassEntity" id="classResultMap">

<id property="classID" column="CLASS_ID" />

<result property="className" column="CLASS_NAME" />

<result property="classYear" column="CLASS_YEAR" />

<association property="teacherEntity" column="TEACHER_ID" select="getTeacher"/>

</resultMap>

<select id="getClassByID" parameterType="String" resultMap="classResultMap">

SELECT * FROM CLASS_TBL CT

WHERE CT.CLASS_ID = #{classID};

</select>

TeacherMapper.xml文件部分内容:

Xml代码

<resultMap type="TeacherEntity" id="teacherResultMap">

<id property="teacherID" column="TEACHER_ID" />

<result property="teacherName" column="TEACHER_NAME" />

<result property="teacherSex" column="TEACHER_SEX" />

<result property="teacherBirthday" column="TEACHER_BIRTHDAY"/>

<result property="workDate" column="WORK_DATE"/>

<result property="professional" column="PROFESSIONAL"/>

</resultMap>

<select id="getTeacher" parameterType="String" resultMap="teacherResultMap">

SELECT *

FROM TEACHER_TBL TT

WHERE TT.TEACHER_ID = #{teacherID}

</select>

2.1.3.2使用resultMap实现联合

与上面同样的功能,查询班级,同时查询器班主任。需在association中添加resultMap(在teacher的xml文件中定义好的),新写sql(查询班级表left join教师表),不需要teacher的select。

修改ClassMapper.xml文件部分内容:

Xml代码

<resultMap type="ClassEntity" id="classResultMap">

<id property="classID" column="CLASS_ID" />

<result property="className" column="CLASS_NAME" />

<result property="classYear" column="CLASS_YEAR" />

<association property="teacherEntity" column="TEACHER_ID" resultMap="teacherResultMap"/>

</resultMap>

<select id="getClassAndTeacher" parameterType="String" resultMap="classResultMap">

SELECT *

FROM CLASS_TBL CT LEFT JOIN TEACHER_TBL TT ON CT.TEACHER_ID = TT.TEACHER_ID

WHERE CT.CLASS_ID = #{classID};

</select>

其中的teacherResultMap请见上面TeacherMapper.xml文件部分内容中。

2.1.4 collection聚集

聚集元素用来处理“一对多”的关系。需要指定映射的Java实体类的属性,属性的javaType(一般为ArrayList);列表中对象的类型ofType(Java实体类);对应的数据库表的列名称;
不同情况需要告诉MyBatis 如何加载一个聚集。MyBatis 可以用两种方式加载:

1. select: 执行一个其它映射的SQL 语句返回一个Java实体类型。较灵活;
2. resultsMap: 使用一个嵌套的结果映射来处理通过join查询结果集,映射成Java实体类型。

例如,一个班级有多个学生。
首先定义班级中的学生列表属性:

Java代码

private List<StudentEntity> studentList;

2.1.4.1使用select实现聚集

用法和联合很类似,区别在于,这是一对多,所以一般映射过来的都是列表。所以这里需要定义javaType为ArrayList,还需要定义列表中对象的类型ofType,以及必须设置的select的语句名称(需要注意的是,这里的查询student的select语句条件必须是外键classID)。

ClassMapper.xml文件部分内容:

Xml代码

<resultMap type="ClassEntity" id="classResultMap">

<id property="classID" column="CLASS_ID" />

<result property="className" column="CLASS_NAME" />

<result property="classYear" column="CLASS_YEAR" />

<association property="teacherEntity" column="TEACHER_ID" select="getTeacher"/>

<collection property="studentList" column="CLASS_ID" javaType="ArrayList" ofType="StudentEntity" select="getStudentByClassID"/>

</resultMap>

<select id="getClassByID" parameterType="String" resultMap="classResultMap">

SELECT * FROM CLASS_TBL CT

WHERE CT.CLASS_ID = #{classID};

</select>

StudentMapper.xml文件部分内容:

Xml代码

<!-- java属性,数据库表字段之间的映射定义 -->

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

<!-- 查询学生list,根据班级id -->

<select id="getStudentByClassID" parameterType="String" resultMap="studentResultMap">

<include refid="selectStudentAll" />

WHERE ST.CLASS_ID = #{classID}

</select>

2.1.4.2使用resultMap实现聚集

使用resultMap,就需要重写一个sql,left join学生表。

Xml代码

<resultMap type="ClassEntity" id="classResultMap">

<id property="classID" column="CLASS_ID" />

<result property="className" column="CLASS_NAME" />

<result property="classYear" column="CLASS_YEAR" />

<association property="teacherEntity" column="TEACHER_ID" resultMap="teacherResultMap"/>

<collection property="studentList" column="CLASS_ID" javaType="ArrayList" ofType="StudentEntity" resultMap="studentResultMap"/>

</resultMap>

<select id="getClassAndTeacherStudent" parameterType="String" resultMap="classResultMap">

SELECT *

FROM CLASS_TBL CT

LEFT JOIN STUDENT_TBL ST

ON CT.CLASS_ID = ST.CLASS_ID

LEFT JOIN TEACHER_TBL TT

ON CT.TEACHER_ID = TT.TEACHER_ID

WHERE CT.CLASS_ID = #{classID};

</select>

其中的teacherResultMap请见上面TeacherMapper.xml文件部分内容中。studentResultMap请见上面StudentMapper.xml文件部分内容中。

2.1.5discriminator鉴别器

有时一个单独的数据库查询也许返回很多不同(但是希望有些关联)数据类型的结果集。鉴别器元素就是被设计来处理这个情况的,还有包括类的继承层次结构。鉴别器非常容易理解,因为它的表现很像Java语言中的switch语句。

定义鉴别器指定了column和javaType属性。列是MyBatis查找比较值的地方。JavaType是需要被用来保证等价测试的合适类型(尽管字符串在很多情形下都会有用)。

下面这个例子为,当classId为20000001时,才映射classId属性。

Xml代码

<resultMap type="liming.student.manager.data.model.StudentEntity" id="resultMap_studentEntity_discriminator">

<id property="studentId" column="STUDENT_ID" javaType="String" jdbcType="VARCHAR"/>

<result property="studentName" column="STUDENT_NAME" javaType="String" jdbcType="VARCHAR"/>

<result property="studentSex" column="STUDENT_SEX" javaType="int" jdbcType="INTEGER"/>

<result property="studentBirthday" column="STUDENT_BIRTHDAY" javaType="Date" jdbcType="DATE"/>

<result property="studentPhoto" column="STUDENT_PHOTO" javaType="byte[]" jdbcType="BLOB" typeHandler="org.apache.ibatis.type.BlobTypeHandler" />

<result property="placeId" column="PLACE_ID" javaType="String" jdbcType="VARCHAR"/>

<discriminator column="CLASS_ID" javaType="String" jdbcType="VARCHAR">

<case value="20000001" resultType="liming.student.manager.data.model.StudentEntity" >

<result property="classId" column="CLASS_ID" javaType="String" jdbcType="VARCHAR"/>

</case>

</discriminator>

</resultMap>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: