1、typeAliase(别名)
是指在配置文件中用简短的名称代替类全名,别名分为系统别名和自定义别名,不区别大小写
首先在config.xml 中添加配置
<typeAliases>
<typeAlias type="com.kgc.mybatis.pojo.Person" alias="Person"></typeAlias>
</typeAliases>
配置完成后再 mapper.xml中 parameterType属性中的地址就可以用简写 Person 代替了。
2、typeHandler
能够完成java数据类型与数据库字段类型映射转换工作。
>第一步:重写typeHandler方法,根据自己的意愿,我这里是固定大写写入数据库,读出来有转换为小写。
package com.kgc.mybatis.typeHandlers;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
public class MyTypeHandler implements TypeHandler<String> {
public String getResult(ResultSet arg0, String arg1) throws SQLException {
return arg0.getString(arg1).toLowerCase();
}
public String getResult(ResultSet arg0, int arg1) throws SQLException {
return arg0.getString(arg1).toLowerCase();
}
public String getResult(CallableStatement arg0, int arg1)
throws SQLException {
return arg0.getString(arg1).toLowerCase();
}
public void setParameter(PreparedStatement arg0, int arg1, String arg2,
JdbcType arg3) throws SQLException {
arg0.setString(arg1, arg2.toUpperCase());
}
}
>第二步:同样在config.xml 中添加配置
<typeHandlers>
<typeHandler handler="com.kgc.mybatis.typeHandlers.MyTypeHandler" javaType="String" jdbcType="VARCHAR"/>
</typeHandlers>
>第三步:配置完成后通过 jdbcType="VARCHAR" 调用自己重写的方法
这里两个写入和读出的例子
写入数据库:
<insert id="addPerson1" parameterType="Person" useGeneratedKeys="true" keyProperty="pid">
insert into t_person values(null,#{pname,jdbcType=VARCHAR},#{age},#{address,jdbcType=VARCHAR})
</insert>
从数据库读出:
<resultMap type="Person" id="Person3" >
<id property="pid" />
<result property="pname" column="person_name" jdbcType="VARCHAR"/>
<result property="age"/>
<result property="address" column="person_address" jdbcType="VARCHAR"/>
</resultMap>
3.resultMap
映射器默认使用resultType 返回数据类型,resultMap是手动定义映射关系
<resultMap type="Person" id="Person3" >
<id property="pid" />
<result property="pname" column="person_name" jdbcType="VARCHAR"/>
<result property="age"/>
<result property="address" column="person_address" jdbcType="VARCHAR"/>
</resultMap>
type="Person" id="Person3" type="Person"调用原返回类型,id="Person3" 定义信息返回数据类型
<result property="pname" column="person_name" jdbcType="VARCHAR"/> 定义映射关系, property="pname" 表示Person中的属性名,column="person_name" 表示数据库表中的字段名。
4、SQL片段
在映射器中不同操作有可能SQL语句出现部分重复的部分,可以使用SQL元素定义重复的SQL片段,然后再需要的位置引用。
<sql id="testsql">
name,age,address
</sql>
<select id="getPersonList" resultType="Person" >
select <include refid="testsql" /> from t_person
</select>
select <include refid="testsql" /> from t_person :<include> 的作用是把id值为testsql 的SQL 片段拼接到当前位置。