我们在做两张表的关联查询时,首先要搞清楚表之间的关系,如商品和商品类型之间的多对一关系
我们在设计两张表时应给商品表添加一个外键指向类型表的主键。
关联之后 商品实体类
@TableId("id") private Integer id ; private Integer tid; private String title; private Integer price; private Integer num; @TableField("created_time") private Date createdTime; @TableField("modified_time") private Date modifiedTime; private StoreType storeType;
StoreMapper.xml要添加的高级映射
<resultMap id="BaseResultMap" type="com.stylefeng.guns.common.persistence.model.Store"> <id column="id" property="id" /> <result column="tid" property="tid"/> <result column="title" property="title"/> <result column="price" property="price"/> <result column="num" property="num" /> <result column="created_time" property="createdTime" /> <result column="modified_time" property="modifiedTime" /> <association property="storeType" javaType="com.stylefeng.guns.common.persistence.model.StoreType"> <id column="id" property="id" /> <result column="name" property="name"/> <result column="status" property="status" /> <result column="created_time" property="createdTime" /> <result column="modified_time" property="modifiedTime" /> </association> </resultMap>
那么关联查询便是
<select id="findAll" resultMap="BaseResultMap"> SELECT g.*,t.name FROM goods g join goods_type t on g.tid = t.id <if test="title != null and title != ''"> WHERE g.title LIKE concat ('%',#{title},'%') </if> order by g.id limit #{page},#{limit} </select>