我們在做兩張表的關聯查詢時,首先要搞清楚表之間的關系,如商品和商品類型之間的多對一關系
我們在設計兩張表時應給商品表添加一個外鍵指向類型表的主鍵。
關聯之后 商品實體類
@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>
