MyBitis(iBitis)系列随笔之一:MyBitis入门实例
MyBitis(iBitis)系列随笔之二:类型别名(typeAliases)与表-对象映射(ORM)
MyBitis(iBitis)系列随笔之三:简单实现CRUD
MyBitis(iBitis)系列随笔之四:多表(多对一查询操作)
MyBitis(iBitis)系列随笔之五:多表(一对多关联查询)
MyBitis(iBitis)系列随笔之六:mybitis与spring集成
类型别名(typeAliases):
作用:通过一个简单的别名来表示一个冗长的类型,这样可以降低复杂度。
类型别名标签typeAliases中可以包含多个typeAlias,如下
<typeAliases>
<typeAlias alias="user" type="com.jefry.User"/>
<typeAlias alias="student" type="com.jefry.student"/>
……
……
……
</typeAliases>
本着简单的原则,我还是接着上一讲实例代码来作修改
在mybatis-config.xml文件增加一个<typeAliases>
代码如下:
<?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="user" type="com.jefry.User"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/jefry/UserMapper.xml"/>
</mappers>
</configuration>
那么在UserMapper.xml文件中type="com.jefry.User"就可以替换为user
如下:
<?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="User">
<!--resultType 表示com.jefry.User这样一个实体对象 -->
<select id="selectUser" parameterType="int" resultType="user">
select * from t_user where id = #{id}
</select>
</mapper>
表-对象映射
上一讲中实例,我们并没有配置表的字段与实体属性之间的关联,但是我们却得到了我们想要的实例对象。原因是我们的t_user表的各个字段名与User类的成员属性名完全一致,一旦t_user表的各个字段名与User类的成员属性名不同(比如t_user某个字段是name,而User的属性却是username)怎么办呢?
MyBitis借助resultMap实现了表-对象映射如下:
<resultMap id="userResultMap" type="user">
<id property="id" column="id"/>
<result property="userName" column="name"/>
<result property="password" column="pass"/>
</resultMap>
根据字面意思我们很容易将字段与属性映射起来。
需要主要的是 resultType="com.jefry.User">变为resultMap="userResultMap"啦。
<select id="selectUser" parameterType="int" resultMap="userResultMap" >
select * from t_user where id = #{id}
</select>
新的UserMapper.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="user">
<resultMap id="userResultMap" type="user">
<id property="id" column="id"/>
<result property="userName" column="name"/>
<result property="password" column="pass"/>
</resultMap>
<!--resultType 表示com.jefry.User这样一个实体对象 -->
<select id="selectUser" parameterType="int" resultMap="userResultMap" >
select * from t_user where id = #{id}
</select>
</mapper>