mybatis 一对一与一对多collection和association的使用
前言
在mybatis如何进行一对一、一对多的多表查询呢?这里用一个简单的例子说明。
一对一
association
association
通常用来映射一对一的关系,例如,有个类PointTypeName
,对应的实体类如下:(getter,setter方法省略)
import java.util.List;
public class PointTypeName{
private static final long serialVersionUID = 1L;
private Integer typeName;
}
有个类
PointsConsump
,对应的实体类如下:
import java.sql.Timestamp;
public class PointsConsump {
private Long key;
private Integer levelKey;
private Integer typeName;
private Integer consumption;
private Integer ticket;
private Integer chance;
private Timestamp reduceAt;
private Timestamp updatedAt;
private Integer version;
private String level;
}
如果我想查询一个 PointsConsump
的时候,也查到 PointsConsump
,可以怎样写呢?在类 PointsConsump
加入一个属性 PointsConsump
import java.util.List;
public class PointTypeName{
private static final long serialVersionUID = 1L;
private Integer typeName;
private PointsConsump pointsConsump;
}
mapper.xml
我在PointsConsump
类的mapper.xml
这样配置(这里一般用id或者key我的表比较特殊)
<resultMap type="hotkidclub.model.points.PointTypeName"
id="pointsMap">
<id column="typeName" property="typeName" />
<association property="pointsConsump" ofType="hotkidclub.model.points.PointsConsump">
<id property="key" column="key" />
<result property="level" column="level" />
<result property="consumption" column="consumption" />
<result property="ticket" column="ticket" />
<result property="chance" column="chance" />
</association>
</resultMap>
一对多,collection,理解了一对一,一对多容易理解。
实体类增加对应属性
import java.util.List;
public class PointTypeName{
private static final long serialVersionUID = 1L;
private Integer typeName;
private List<PointsConsump> pointsConsump;
}
mapper.xml
我在PointsConsump
类的mapper.xml
这样配置(这里一般用id或者key我的表比较特殊)
<resultMap type="hotkidclub.model.points.PointTypeName" id="pointsMap">
<id column="typeName" property="typeName" />
<collection property="pointsConsump" ofType="hotkidclub.model.points.PointsConsump">
<id property="key" column="key"/>
<result property="level" column="level"/>
<result property="consumption" column="consumption"/>
<result property="ticket" column="ticket"/>
<result property="chance" column="chance"/>
</collection>
</resultMap>
标签属性介绍
- id:命名空间中的唯一标识符,可以被用来引用这条语句
- parameterType:表示查询语句传入参数的类型的完全限定名或别名,支持基础数 据类型和复杂数据类型。
- resultType:查询语句返回结果类型的完全限定名或别名。
- property : 对象属性的名称
- javaType :对象属性的类型
- column :所对应的外键字段名称
- select :使用另一个查询封装的结果
- ofType :collection中的属性, 用于指定集合中元素的对象类型。
特别注意:
表中主键字段要有所区分,不能都写成id,要写成
user_id
、card_id
,这一类的反正要有所区分,不然查询的时候会查不到完整的数据。
最后
-
更多参考精彩博文请看这里:《陈永佳的博客》
-
喜欢博主的小伙伴可以加个关注、点个赞哦,持续更新嘿嘿!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/97582.html