1. 程式人生 > >MyBatis——一對多、一對一關係,collection、association

MyBatis——一對多、一對一關係,collection、association

實體類兩個:

user類:

package com.pojo;
/**
*使用者
*/
public class User{
    private int userId;//使用者ID
    private String username;//使用者名稱
    private String password;//使用者密碼
    private String address;//使用者地址
    private String sex;//性別
    
    private List<Text> list;//使用者所釋出帖子的集合
    
    //get/set省略
}

text類:

package com.pojo;
/**
*帖子
*/
public class Text{
    private int textId;//帖子的ID
    private int userId;//使用者ID
    private String title;//帖子標題
    private String context;//帖子內容
    private Date time;//帖子釋出時間
    
    private User user;//使用者物件
    
    //get/set省略
}

 

 

 User_SQL_Mapper.xml

<
mapper namespace="com.dao.UserDao"> <resultMap type="com.pojo.User" id="userMap"> <id column="user_id" property="userId"/> <result column="username" property="username"/> <result column="password" property="password"/> <result column="address"
property="address"/> <result column="sex" property="sex"/> <!-- 一對多關係 --> <collection property="list" ofType="com.pojo.Text"> <result column="text_id" property="textId"/> <result column="title" property="title"/> <result column="context" property="context"/> </collection> </resultMap> </mapper>

 

 Text_SQL_Mapper.xml:

<mapper namespace="com.dao.TextDao">
    <resultMap type="com.pojo.Text" id="textMap">
        <id column="text_id" property="textId"/>
        <result column="title" property="title"/>
        <result column="context" property="context"/>
        <result column="time" property="time"/>
       
        <!-- 一對一關係 -->
        <association property="user" javaType="com.pojo.User">
            <result column="username" property="username"/>
            <result column="password" property="password"/>
            <result column="address" property="address"/>
            <result column="sex" property="sex"/>
        </association>
    </resultMap>
</mapper>