1: resultMap标签
当我们的数据库字段与实体类的属性不一致时,就需要使用该标签进行一一映射。
2:使用情况
2.1 简单查询
<resultMap id="这个resultMap的id" type="对应实体类的全限定类名">
<id column="id" property="id"></id>
<result column="username" property="name"></result>
<result column="author" property="author"></result>
<result column="number" property="number"></result>
.............
colum对应数据库的字段,property对应实体类的属性
</resultMap>
他表示对数据按照什么样的规则进行一一映射,如:
<!-- 根据编号查找书籍-->
<select id="SelectbooksByNumber" parameterType="String" resultMap="名字">
select * from book where number=#{number};
</select>
上面的查找结果按照你给的resultMap的对应规则进行映射。
2.2 一对一
association 属性用于处理一对一关系(One-to-One)的映射。它允许我们在映射文件中定义一个对象类型的属性,并将其与其他实体类关联起来。需要注意的是你sql语句查出来的列名称是别名,那你就要填别名,就不是你数据库的列名称了。
以下是 association 属性的详细说明:
- property:指定对象属性的名称,它对应于 JavaBean 中的属性名,用于设置或获取映射结果。
- column:指定数据库中与对象关联的列名。列如传递到子查询中{sid=id},id必须出现在父查询的结果集中,子查询中要使用sid
- javaType:指定对象属性的类型。通常,MyBatis会根据返回类型自动推断出对象类型,所以很少需要显式设置该属性。
- select:指定用于加载对象的 SQL 语句或引用一个已经定义的
<select>
元素。(它会从column 属性指定的列中检索数据,作为参数传递给目标 select 语句)- fetchType:指定对象的加载方式。可以设置为 lazy(延迟加载)或 eager(即时加载)。默认为 eager。
<resultMap id="userMap" type="com.sweet.shiro.entry.User">
<id column="uid" property="id"/>
<result column="username" property="username"/>
<!--角色信息-->
<!-- 一对一 -->
<association property="role" javaType="com.sweet.shiro.entry.Role">
<id column="id" property="id"/>
<result column="rname" property="name"/>
</association>
返回结果:User
User中含有单个Role属性 即一对一的关系
JavaType是用来指定pojo中属性的类型
2.3 一对多
collection 属性用于处理一对多关系(One-to-Many)的映射。它允许我们在映射文件中定义一个集合类型的属性,将其与其他实体类关联起来。同样和一对一 一样需要注意列名称。
以下是 collection 属性的详细说明:
- property:指定集合属性的名称,它对应于 JavaBean 中的属性名,用于设置或获取映射结果。
- column:指定数据库中与对象关联的列名。列如传递到子查询中{sid=id},id必须出现在父查询的结果集中,子查询中要使用sid
- javaType:指定集合对象的类型。通常,MyBatis会根据返回类型自动推断出集合类型,所以很少需要显式设置该属性。
- ofType:指定集合中元素的类型。这是必需的,因为 MyBatis 需要知道如何映射从数据库中获取的数据到具体的对象类型。
- select:指定用于加载对象的 SQL 语句或引用一个已经定义的
<select>
元素。(它会从column 属性指定的列中检索数据,作为参数传递给目标 select 语句)- fetchType:指定集合的加载方式。可以设置为 lazy(延迟加载)或 eager(即时加载)。默认为 eager。
<resultMap id="userMap" type="com.sweet.shiro.entry.User">
<id column="uid" property="id"/>
<result column="username" property="username"/>
<!--角色信息-->
<collection property="roles" javaType="list" ofType="com.sweet.shiro.entry.Role">
<id column="id" property="id"/>
<result column="rname" property="name"/>
</collection>
</resultMap>
<select id="findRolesByUserName" parameterType="String" resultMap="userMap">
select u.id uid ,u.username,r.id,r.`name` rname
from t_user u
LEFT JOIN t_user_role ur
on u.id = ur.roleId
LEFT JOIN t_role r
on ur.roleId = r.id
where u.username = #{username}
</select>
返回结果:User
User中含有Role属性集合 一对多的关系
JavaType是用来指定pojo中属性的类型,
ofType指定的是 映射到list集合属性中pojo的类型
其中Role属性集合为List
pojo
public class User implements Serializable {
private Integer id;
private String username;
private String password;
private String salt;
private Integer status; // 用户状态 0: 正常 1:禁用 2:锁定
//角色集合
private List<Role> roles;
role表
user表
user与role的映射表