当数据库字段名与实体类对应的属性名不一致时,有两种解决方式:
- 在xml文件中指定resultMap,指定id,下面需要的直接引用id就可以;
- 使用注解开发时,通过注解@Results来指定对应关系
resultMap标签
resultMap 标签可以建立查询的列名和实体类的属性名称不一致时建立对应关系。从而实现封装。
在 select 标签中使用 resultMap 属性指定引用即可。同时 resultMap 可以实现将查询结果映射为复杂类型的 pojo,比如在查询结果映射对象中包括 pojo 和 list 实现一对一查询和一对多查询。
使用:
<resultMap type="com.itheima.domain.User" id="userMap">
<id column="id" property="userId"/>
<result column="username" property="userName"/>
<result column="sex" property="userSex"/>
<result column="address" property="userAddress"/>
<result column="birthday" property="userBirthday"/>
</resultMap>
其中:
id 标签:用于指定主键字段
result 标签:用于指定非主键字段
column 属性:用于指定数据库列名
property 属性:用于指定实体类属性名称
@Results
源码:
/**
* @author Clinton Begin
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({})
public @interface Result {
boolean id() default false;
String column() default "";
String property() default "";
Class<?> javaType() default void.class;
JdbcType jdbcType() default JdbcType.UNDEFINED;
Class<? extends TypeHandler> typeHandler() default UnknownTypeHandler.class;
One one() default @One;
Many many() default @Many;
}
主要成员变量:
- id:是否为主键,默认false。
- column:数据库字段名
- porperty:实体类属性名
- jdbcType:数据库字段数据类型
使用:
@Select("select * from orders")
@Results({
@Result(id = true,column = "id",property = "id"),
@Result(column = "orderNum",property = "orderNum"),
@Result(column = "orderTime",property = "orderTime"),
@Result(column = "peopleCount",property = "peopleCount"),
@Result(column = "orderDesc",property = "orderDesc"),
@Result(column = "payType",property = "payType"),
@Result(column = "orderStatus",property = "orderStatus"),
@Result(column = "productId",property = "product",one = @One(select = "cn.ziwei.dao.IProductDao.findById"))
})
public List<Orders> findAll() throws Exception;
@one的使用:
子查询,也就是在查询时,需要执行另一条语句查询关联内容,且时一一对应的时候使用。
比如上面,执行的是查询orders表的所有,而productId是一个外键,关联的是product表中的一行信息,且实体类的属性是一个Product,所以使用@one
@many:
与@One类似,只不过如果使用@One查询到的结果是多行,会抛出TooManyResultException异常,这种时候应该使用的是@Many注解,实现一对多的查询。比如在需要查询学生信息和每次考试的成绩信息时。