高级映射:一对多 表的关联查询


我们在做两张表的关联查询时,首先要搞清楚表之间的关系,如商品和商品类型之间的多对一关系

我们在设计两张表时应给商品表添加一个外键指向类型表的主键。

关联之后  商品实体类

 @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>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM