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>
原文地址:https://www.cnblogs.com/whx20100101/p/9807103.html