Mybatis 一對多

自己練習,自己記錄。

假設有 student 和 goods 兩張表

應用場景一: 一個student可以購買多個goods     一對多

Student.xml文件如下:

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hz.platform.demo.dao.StudentDao">
    <!-- 中文文檔https://mybatis.org/mybatis-3/zh/dynamic-sql.html-->
    <resultMap id="studentResult" type="com.hz.platform.demo.entity.Student">
        <result column="uuid" property="uuid" jdbcType="VARCHAR"/>
        <result column="stu_name" property="stuName" jdbcType="VARCHAR"/>
        <result column="address" property="address" jdbcType="VARCHAR"/>
        <result column="age" property="age" jdbcType="INTEGER"/>
        <result column="birthday" property="birthday" jdbcType="TIMESTAMP"/>
        <result column="gender" property="gender" jdbcType="VARCHAR"/>
        <!-- 一個學生可以購買多個商品-->
        <!-- collection標籤內的屬性解釋
             property="goodsList":表示這名student購買過的Goods集合,
             column="studentId":Goods表與student表關聯的Id,
             ofType="com.hz.platform.demo.entity.Goods": 關聯的實體-->
        <collection property="goodsList" column="studentId" ofType="com.hz.platform.demo.entity.Goods">
            <result property="uuid" column="uuid" jdbcType="VARCHAR"/>
            <result property="studentId" column="studentId" jdbcType="VARCHAR"/>
            <result property="price" column="price" jdbcType="DOUBLE"/>
            <result property="goodsName" column="goodsName" jdbcType="VARCHAR"/>
        </collection>
    </resultMap>
    <!-- 一對多-->
    <select id="findOneToMany" resultMap="studentResult">
        select stu.*,g.*
        from student stu ,goods g
        <trim prefix="where" prefixOverrides="AND|OR">
            and stu.uuid = g.studentId
        </trim>
    </select>
</mapper>

Goods.xml如下

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hz.platform.demo.dao.GoodsDao">
    <resultMap id="goodsResult" type="com.hz.platform.demo.entity.Goods">
        <result property="goodsName" column="goodsName" jdbcType="VARCHAR"/>
        <result property="disc" column="disc" jdbcType="VARCHAR"/>
        <result property="price" column="price" jdbcType="DOUBLE"/>
        <result property="uuid" column="uuid" jdbcType="VARCHAR"/>
        <result property="studentId" column="studentId" jdbcType="VARCHAR"/>
    </resultMap>
</mapper>

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章