Mybatis查询:持有关系、中间表、时间范围

前置技能

了解mybatis、对mapper类和mapper.xml配置有基础认识

持有

例如一件售后商品,实质是一件商品+售后信息;

思路:售后商品是商品,售后商品包含商品,而具有更多的信息;
在建表时,可以考虑做一张售后商品表,具有售后信息,并将商品的主键作为其中的一个字段。

用Java语言来描述的话:售后商品持有一个商品,商品是售后商品一个成员属性;

Java代码
public class AftersalesProduct {
    private Integer apid;			//主键id
    private String message;		//售后信息
    
    private Integer pid;			//商品id
    private Product prodcut;			//持有一个商品
	/*
	以下省略
	*/
}
XML和mapper类
  <resultMap id="BaseResultMap" type="group3.entity.AftersalesProduct">
	    <id column="ap_id" jdbcType="INTEGER" property="apid" />
	    <result column="message" jdbcType="VARCHAR" property="message" />
	    <result column="pid" jdbcType="INTEGER" property="pid" />
	   <association column="pid" property="prodcut" javaType="src.entity.Prodcut" select="src.dao.ProdcutMapper.selectByPrimaryKey"></association>
  </resultMap>

association详解
使用select指定的语句查询,查询参数是column,查询结果是javaType类型,赋值给property这个属性。




中间表、多对多关系

商品可能被多个售后单持有,你退了一台iPhone4,我也可以退一台iPnoe4;
一个售后单有多个商品,你可以同时退一台iPhone4和华为P30;
这个时候就需要使用中间表。

售后商品表:售后信息 (这次不加商品id了)
商品表:商品信息
中间表:售后单id+商品id

Java代码
public class AftersalesProduct {
    private Integer apid;			//主键id
    private String message;		//售后信息
   // private Integer pid;			//这次不要商品id了
    private List<Product> prodcuts;		//持有好多商品
	/*
	以下省略
	*/
}
XML和mapper类

售后商品的resultMap
AftersalesProductMapper.xml

  <resultMap id="BaseResultMap" type="group3.entity.AftersalesProduct">
	    <id column="ap_id" jdbcType="INTEGER" property="apid" />
	    <result column="message" jdbcType="VARCHAR" property="message" />
	   <collection  column="ap_id" property="products" ofType="group3.entity.Prodcut" select="src.dao.ProdcutMapper.selectByKeys"></collection>
  </resultMap>

collection 标签中使用到的查询方法
ProdcutMapper.xml

    <select id="selectByKeys" parameterType="java.lang.Integer" resultType="src.dao.Prodcut" >
    select * from 商品表
    where 商品主键 in (select 商品主键 from 中间表 where 售后单主键=#{售后单主键}) 
  </select>

collectioncolumn指定的,售后单主键传入到select的查询语句中;
查询语句通过子查询,先查出售后单对应的所有商品id;
再查询这些商品id对应的商品;




时间区间

如果要查询一定时间内所有的售后单,就需要用到时间区间查询了;

基本写法都是在select标签里添加:

  		 <if test="beginTime !=null ">
  			AND createdate &gt;= #{beginTime}
  		</if>
  		  <if test="endTime !=null ">
  			AND createdate &lt;= #{endTime}
  		</if>

而在传入参数上,有通过map传入,和通过属性传入;
属性的话就是加两个属性,在查询的service方法中每次查询后置null;
map就是写工具类或者手put咯;

public class AftersalesProduct {
    private Integer apid;			//主键id
    private String message;		//售后信息
   // private Integer pid;			//这次不要商品id了
    private List<Product> prodcuts;		//持有好多商品
	/*
	以下省略
	*/
	private Date beginTime;		//查询时间区间用的 不上传数据库 每次查询后置null
    private Date endTime;
}

ps.经测试,时间区间查询,可以传util.Date对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值