您的位置:首页 > 编程语言 > Java开发

Spring中的Mybatis基础

2016-04-14 16:52 507 查看
1、配置实例

(1)mybatis包

<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
(2)映射文件XXXMapper.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="xxx.web.mapper.XXXMapper" >

<insert id="insert"  parameterType="Metrics" useGeneratedKeys="true" keyProperty="id" >
INSERT INTO metrics ...
</insert>

<insert id="insertAll"  parameterType="List">
INSERT INTO metrics ...
</insert>

<select id="getLastRecordByAppId" resultType="Metrics">
select ...
</select>
</mapper>
(3)接口文件XXXMapperDao.java

public interface XXXMapperDao {

Long insert(Metrics metrics);

Long insertAll(@Param("list")List<Metrics> list);

List<Metrics> getLastRecordByAppId(@Param("appId")String appId,@Param("date")String date);
}
(4)扫描映射文件配置

<!-- scan for mappers and let them be autowired -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="xxx.web.mapper" />//接口所在的包名,包括子包
<property name="sqlSessionFactoryBeanName" value="xxxSqlSessionFactory"/>
</bean>
(5)配置SqlsessionFactory

<!-- define the SqlSessionFactory -->
<bean id="sysSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="sysDataSource" />
<property name="typeAliasesPackage" value="com.mogujie.mario.web.entity;com.mogujie.mario.web.vo" />//也可以在总装配置文件中定义别名
<property name="configurationProperties">//也可以在总装配置文件中设置
<props>
<prop key="cacheEnabled">true</prop>
<!-- 查询时,关闭关联对象即时加载以提高性能 -->
<prop key="lazyLoadingEnabled">true</prop>
<!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指定),不会加载关联表的所有字段,以提高性能 -->
<prop key="aggressiveLazyLoading">false</prop>
<!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->
<prop key="multipleResultSetsEnabled">true</prop>
<!-- 允许使用列标签代替列名 -->
<prop key="useColumnLabel">true</prop>
<!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 -->
<prop key="useGeneratedKeys">true</prop>
<!-- 给予被嵌套的resultMap以字段-属性的映射支持 -->
<prop key="autoMappingBehavior">FULL</prop>
<!-- 对于批量更新操作缓存SQL以提高性能  -->
<prop key="defaultExecutorType">BATCH</prop>
<!-- 数据库超过25000秒仍未响应则超时 -->
<prop key="defaultStatementTimeout">25000</prop>
</props>
</property>
<property name="mapperLocations" value="classpath:com/xxx/mybatis/*.xml"/>//导入mapper映射文件,这样就不需要在总装配置文件中逐个列出,如果java接口与xml文件在同一相对路径下,则不需要配置
</bean>


这样,就可以通过@Autowired自动注入接口映射的Bean了。

@Transactional
@Service
public class XXXService{
@Autowired
private XXXMapperDao xxxDao;

public void insert(Metrics metrics){
xxxDao.insert(metrics);
}
}

2、resultMap

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

<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

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

 

(2)association

(3)collection

参考:http://limingnihao.iteye.com/blog/781878

//todo

3、增删改查

(1)select

<!-- 查询学生,根据id -->
<select id="getStudent" parameterType="String" resultMap="studentResultMap">
SELECT ST.STUDENT_ID,
ST.STUDENT_NAME,
ST.STUDENT_SEX,
ST.STUDENT_BIRTHDAY,
ST.CLASS_ID
FROM STUDENT_TBL ST
WHERE ST.STUDENT_ID = #{studentID}
</select>


select 语句属性配置细节: 
属性描述取值默认
id在这个模式下唯一的标识符,可被其它语句引用  
parameterType传给此语句的参数的完整类名或别名  
resultType语句返回值类型的整类名或别名。注意,如果是集合,那么这里填写的是集合的项的整类名或别名,而不是集合本身的类名。(resultType 与resultMap 不能并用)  
resultMap引用的外部resultMap 名。结果集映射是MyBatis 中最强大的特性。许多复杂的映射都可以轻松解决。(resultType 与resultMap 不能并用)  
flushCache如果设为true,则会在每次语句调用的时候就会清空缓存。select 语句默认设为falsetrue|falsefalse
useCache如果设为true,则语句的结果集将被缓存。select 语句默认设为false true|false false

timeout 设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定
true|falsefalse
timeout 设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定正整数未设置
fetchSize设置一个值后,驱动器会在结果集数目达到此数值后,激发返回,默认为不设值,由驱动器自己决定正整数驱动器决定
statementTypestatement,preparedstatement,callablestatement。

预准备语句、可调用语句
STATEMENT

PREPARED

CALLABLE
PREPARED
resultSetTypeforward_only,scroll_sensitive,scroll_insensitive

只转发,滚动敏感,不区分大小写的滚动
FORWARD_ONLY

SCROLL_SENSITIVE

SCROLL_INSENSITIVE
驱动器决定
(2)insert

<!-- 插入学生 自动主键-->
<insert id="insertStudentAutoKey" parameterType="StudentEntity">
<selectKey keyProperty="studentID" resultType="String" order="BEFORE">
select nextval('student')
</selectKey>
INSERT INTO STUDENT_TBL (STUDENT_ID,
STUDENT_NAME,
STUDENT_SEX,
STUDENT_BIRTHDAY,
CLASS_ID)
VALUES   (#{studentID},
#{studentName},
#{studentSex},
#{studentBirthday},
#{classEntity.classID})
</insert>
insert可以使用数据库支持的自动生成主键策略,设置useGeneratedKeys=”true”,然后把keyProperty 设成对应的列,就搞定了。比如说上面的StudentEntity 使用auto-generated 为id 列生成主键.
 还可以使用selectKey元素。下面例子,使用mysql数据库nextval('student')为自定义函数,用来生成一个key。

insert语句属性配置细节:
属性描述取值默认
id在这个模式下唯一的标识符,可被其它语句引用  
parameterType传给此语句的参数的完整类名或别名  
flushCache如果设为true,则会在每次语句调用的时候就会清空缓存。select 语句默认设为falsetrue|falsefalse
useCache如果设为true,则语句的结果集将被缓存。select 语句默认设为false true|false false

timeout 设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定
true|falsefalse
timeout 设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定正整数未设置
fetchSize设置一个值后,驱动器会在结果集数目达到此数值后,激发返回,默认为不设值,由驱动器自己决定正整数驱动器决定
statementTypestatement,preparedstatement,callablestatement。

预准备语句、可调用语句
STATEMENT

PREPARED

CALLABLE
PREPARED
useGeneratedKeys告诉MyBatis 使用JDBC 的getGeneratedKeys 方法来获取数据库自己生成的主键(MySQL、SQLSERVER 等

关系型数据库会有自动生成的字段)。默认:false
true|falsefalse
keyProperty标识一个将要被MyBatis 设置进getGeneratedKeys 的key 所返回的值,或者为insert 语句使用一个selectKey

子元素。
  
 

 

selectKey语句属性配置细节:

 
属性描述取值
keyPropertyselectKey 语句生成结果需要设置的属性。 
resultType生成结果类型,MyBatis 允许使用基本的数据类型,包括String 、int类型。 
order可以设成BEFORE 或者AFTER,如果设为BEFORE,那它会先选择主键,然后设置keyProperty,再执行insert语句;如果设为AFTER,它就先运行insert 语句再运行selectKey 语句,通常是insert 语句中内部调用数据库(像Oracle)内嵌的序列机制。 BEFORE

AFTER
statementType像上面的那样, MyBatis 支持STATEMENT,PREPARED和CALLABLE 的语句形式, 对应Statement ,PreparedStatement 和CallableStatement 响应
(3)update

<!-- 更新学生信息 -->
<update id="updateStudent" parameterType="StudentEntity">
UPDATE STUDENT_TBL
SET STUDENT_TBL.STUDENT_NAME = #{studentName},
STUDENT_TBL.STUDENT_SEX = #{studentSex},
STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},
STUDENT_TBL.CLASS_ID = #{classEntity.classID}
WHERE STUDENT_TBL.STUDENT_ID = #{studentID};
</update>
(4)delete

<!-- 删除学生 -->
<delete id="deleteStudent" parameterType="StudentEntity">
DELETE FROM STUDENT_TBL WHERE STUDENT_ID = #{studentID}
</delete>


update、delete语句属性配置细节:

 
属性描述取值默认
id在这个模式下唯一的标识符,可被其它语句引用  
parameterType传给此语句的参数的完整类名或别名  
flushCache如果设为true,则会在每次语句调用的时候就会清空缓存。select 语句默认设为falsetrue|falsefalse
useCache如果设为true,则语句的结果集将被缓存。select 语句默认设为false true|false false

timeout 设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定
true|falsefalse
timeout 设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定正整数未设置
fetchSize设置一个值后,驱动器会在结果集数目达到此数值后,激发返回,默认为不设值,由驱动器自己决定正整数驱动器决定
statementTypestatement,preparedstatement,callablestatement。

预准备语句、可调用语句
STATEMENT

PREPARED

CALLABLE
PREPARED
4、Sql元素用来定义一个可以复用的SQL 语句段,供其它语句调用。比如:

<!-- 复用sql语句  查询student表所有字段 -->
<sql id="selectStudentAll">
SELECT ST.STUDENT_ID,
ST.STUDENT_NAME,
ST.STUDENT_SEX,
ST.STUDENT_BIRTHDAY,
ST.CLASS_ID
FROM STUDENT_TBL ST
</sql>
这样,在select的语句中就可以直接引用使用了,将上面select语句改成:

<!-- 查询学生,根据id -->
<select id="getStudent" parameterType="String" resultMap="studentResultMap">
<include refid="selectStudentAll"/>
WHERE ST.STUDENT_ID = #{studentID}
</select>
5、Parameters

(1)基本类型参数

<!-- 查询学生list,根据入学时间  -->
<select id="getStudentListByDate"  parameterType="Date" resultMap="studentResultMap">
SELECT *
FROM STUDENT_TBL ST LEFT JOIN CLASS_TBL CT ON ST.CLASS_ID = CT.CLASS_ID
WHERE CT.CLASS_YEAR = #{classYear};
</select>
(2)java实体类型参数

<!-- 查询学生list,like姓名、=性别,参数entity类型 -->
<select id="getStudentListWhereEntity" parameterType="StudentEntity" resultMap="studentResultMap">
SELECT * from STUDENT_TBL ST
WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')
AND ST.STUDENT_SEX = #{studentSex}
</select>
(3)Map参数

<!-- 查询学生list,=性别,参数map类型 -->
<select id="getStudentListWhereMap" parameterType="Map" resultMap="studentResultMap">
SELECT * from STUDENT_TBL ST
WHERE ST.STUDENT_SEX = #{sex}
AND ST.STUDENT_SEX = #{sex}
</select>
(4)多参数

public List<StudentEntity> getStudentListWhereParam(@Param(value = "name") String name, @Param(value = "sex") String sex, @Param(value = "birthday") Date birthdar, @Param(value = "classEntity") ClassEntity classEntity);
<!-- 查询学生list,like姓名、=性别、=生日、=班级,多参数方式 -->
<select id="getStudentListWhereParam" resultMap="studentResultMap">
SELECT * from STUDENT_TBL ST
<where>
<if test="name!=null and name!='' ">
ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{name}),'%')
</if>
<if test="sex!= null and sex!= '' ">
AND ST.STUDENT_SEX = #{sex}
</if>
<if test="birthday!=null">
AND ST.STUDENT_BIRTHDAY = #{birthday}
</if>
<if test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' ">
AND ST.CLASS_ID = #{classEntity.classID}
</if>
</where>
</select>
6、标签

(1)if

<if test="studentName !=null ">
ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')
</if>
<if test="studentSex != null and studentSex != '' ">
AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}
</if>
(2)if+where

<where>
<if test="studentName !=null "> ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%') </if> <if test="studentSex != null and studentSex != '' "> AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER} </if>
</where>
(3)if+set

UPDATE STUDENT_TBL
<set>
<if test="studentName != null and studentName != '' ">
STUDENT_TBL.STUDENT_NAME = #{studentName},
</if>
</set>
WHERE STUDENT_TBL.STUDENT_ID = #{studentId};
(4)if+trim

<trim prefix="WHERE" prefixOverrides="AND|OR">
<if test="studentName !=null "> ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%') </if> <if test="studentSex != null and studentSex != '' "> AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER} </if>
</trim>

UPDATE STUDENT_TBL
<trim prefix="SET" suffixOverrides=",">
<if test="studentName != null and studentName != '' ">
STUDENT_TBL.STUDENT_NAME = #{studentName},
</if>
<if test="studentSex != null and studentSex != '' ">
STUDENT_TBL.STUDENT_SEX = #{studentSex},
</if>
</trim>
WHERE STUDENT_TBL.STUDENT_ID = #{studentId}
(5)choose

<where>
<choose>
<when test="studentName !=null ">
ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')
</when >
<when test="studentSex != null and studentSex != '' ">
AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}
</when >
<when test="studentId != null and studentId != '' ">
AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}
</when >
<otherwise>
</otherwise>
</choose>
</where>
(6)foreach,通常是用于IN 条件

public List<StudentEntity> getStudentListByClassIds_foreach_array(String[] classIds);
<!— 7.1 foreach(循环array参数) - 作为where中in的条件 -->
<select id="getStudentListByClassIds_foreach_array" resultMap="resultMap_studentEntity">
SELECT ST.STUDENT_ID,
ST.STUDENT_NAME,
ST.STUDENT_SEX,
ST.STUDENT_BIRTHDAY,
ST.STUDENT_PHOTO,
ST.CLASS_ID,
ST.PLACE_ID
FROM STUDENT_TBL ST
WHERE ST.CLASS_ID IN
<foreach collection="array" item="classIds"  open="(" separator="," close=")">
#{classIds}
</foreach>
</select>
public List<StudentEntity> getStudentListByClassIds_foreach_list(List<String> classIdList);
<!-- 7.2 foreach(循环List<String>参数) - 作为where中in的条件 -->
<select id="getStudentListByClassIds_foreach_list" resultMap="resultMap_studentEntity">
SELECT ST.STUDENT_ID,
ST.STUDENT_NAME,
ST.STUDENT_SEX,
ST.STUDENT_BIRTHDAY,
ST.STUDENT_PHOTO,
ST.CLASS_ID,
ST.PLACE_ID
FROM STUDENT_TBL ST
WHERE ST.CLASS_ID IN
<foreach collection="list" item="classIdList"  open="(" separator="," close=")">
#{classIdList}
</foreach>
</select>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mybatis