类型别名(typeAliases): 作用:通过一个简单的别名来表示一个冗长的类型,这样可以降低复杂度。 类型别名标签typeAliases中可以包含多个typeAlias,如下
[html] view plain copy <typeAliases> <typeAlias alias="user" type="com.jefry.User"/> <typeAlias alias="student" type="com.jefry.student"/> …… …… …… </typeAliases>本着简单的原则,我还是接着上一讲实例代码来作修改 在mybatis-config.xml文件增加一个<typeAliases> 代码如下:
[html] view plain copy <?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 如下:
[html] view plain copy <span style="font-size:14px;"><?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> </span>表-对象映射
上一讲中实例,我们并没有配置表的字段与实体属性之间的关联,但是我们却得到了我们想要的实例对象。原因是我们的t_user表的各个字段名与User类的成员属性名完全一致,一旦t_user表的各个字段名与User类的成员属性名不同(比如t_user某个字段是name,而User的属性却是username)怎么办呢? MyBitis借助resultMap实现了表-对象映射如下:
[html] view plain copy <span style="color:#000000;"><resultMap id="userResultMap" type="user"> <id property="id" column="id"/> <result property="userName" column="name"/> <result property="password" column="pass"/> </resultMap></span>根据字面意思我们很容易将字段与属性映射起来。 需要主要的是 resultType="com.jefry.User">变为resultMap="userResultMap"啦。
[html] view plain copy <span style="color:#000000;"> <select id="selectUser" parameterType="int" resultMap="userResultMap" > select * from t_user where id = #{id} </select></span>新的UserMapper.xml代码如下:
[html] view plain copy <span style="color:#000000;"><?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></span>