<selectid="getUserById"resultType="User">
select *
from user
where id = #{userId}
</select>
1. 这里使用resultType中的User就是java中对应bean类
2. 这样操作这个实体类可以被映射到ResultSet上
3. 这样操作的时候mybatis会自动创建一个resultMap并且根据属性名成映射到实体类上,如果名称不匹配可以设置在sql上设置别名
<selectid="getUserById"resultType="map">
select *
from user
where id = #{userId}
</select>
1. resultType也可以直接映射为map
2. 这样可以把所有的值都映射到HashMap上
多表查询(当数据库字段和实体类不可以对应的情况)
一个实体类中包含另一个实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String name;
private String password;
private UserType userType;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserType {
private Integer id;
private Integer userId;
private String name;
}
1. 当前User类中还有一个UserType的类
2. 比如现在的查询条件是根据id查询User中对应数据同时查询UserType中的关联数据,这个时候单独使用resultType就不好处理啦,这个时候应该使用resultMap来处理
<selectid="getUserById"resultMap="useResult">
select u.id, u.name, u.pwd, t.name tname
from user u
left join user_type t
on u.id = t.user_id
where u.id = #{userId}
</select><resultMapid="useResult"type="User"><resultproperty="id"column="id"/><resultproperty="name"column="name"/><resultproperty="password"column="pwd"/><associationproperty="userType"javaType="UserType"><resultproperty="userId"column="user_id"/><resultproperty="name"column="tname"/></association></resultMap>
4. 在查询多张表的时候如果多个表中字段有重名记得重命名
5. resultMap="useResult"中的useResult就是对应resultMap标签中的id,resultMap标签中的type就是对应最终要返回的实体类
6. result表示一个一个对应的返回值,property表示实体类字段名称,column表示数据库字段达成对应关系
7. association表示一个对象因为上文中User类中的是一个对象所以用这个标签,property在User这个类中当前实体类的名称, javaType表示当前对应的实体类
一个实体类中包含一个集合
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String name;
private String password;
private List<UserType> userList;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserType {
private Integer id;
private Integer userId;
private String name;
}
1. 当前User类中还有一个userList
<selectid="getUserById"resultMap="useResult">
select u.id, u.name, u.pwd, t.name tname
from user u
left join user_type t
on u.id = t.user_id
where u.id = #{userId}
</select><resultMapid="useResult"type="User"><resultproperty="id"column="id"/><resultproperty="name"column="name"/><resultproperty="password"column="pwd"/><collectionproperty="userList"ofType="UserType"><resultproperty="userId"column="user_id"/><resultproperty="name"column="tname"/></collection></resultMap>
1. collection表示集合,property表示在User类中这个实体类的名称,ofType表示当前对应的实体类