前置技能
了解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>
collection
将column
指定的,售后单主键传入到select
的查询语句中;
查询语句通过子查询,先查出售后单对应的所有商品id;
再查询这些商品id对应的商品;
时间区间
如果要查询一定时间内所有的售后单,就需要用到时间区间查询了;
基本写法都是在select标签里添加:
<if test="beginTime !=null ">
AND createdate >= #{beginTime}
</if>
<if test="endTime !=null ">
AND createdate <= #{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对象。