欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【Mybatis_POJO包装类型】关于一个实体类装多个实体类如何映射

程序员文章站 2022-06-15 12:08:44
...

初学Mybatis框架,其实这个是我个人自己通过多表查询延伸想的,为了查询的时候避免查询出不需要的数据。其实学到后面可以用懒加载完成,不必那么繁琐,但这是我还未接触后面知识想到的,单纯的想记录一下。话不多说,先上代码:

//关键映射文件配置
 <resultMap id="userAnduserInfo" type="QueryVo">
        <association property="user" javaType="User">
        <id column="id" property="id"/>
        <result column="username" property="username"/>
        <result column="birthday" property="birthday"/>
        <result column="sex" property="sex"/>
        <result column="address" property="address"/>
        </association>
        <association property="userInfo" javaType="userInfo">
            <id column="id" property="id"/>
            <result column="height" property="height"/>
            <result column="weight" property="weight"/>
            <result column="married" property="married"/>
        </association>
    </resultMap>

//查询语句
<select id="findUserAndUserInfo" resultMap="userAnduserInfo" resultType="QueryVo" parameterType="int">
        SELECT * FROM USER u INNER JOIN user_info i ON u.id = i.id WHERE u.id=#{uid};
</select>

//User类
public class User {
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
    ......(此处省略构造/get/set方法)
    }


    //UserInfo类
    // 用户的扩展信息
public class UserInfo {
    private Integer id;
    private double height;
    private double weight;
    private boolean married;
    ......
    }


    //中间QueryVo类
    public class QueryVo {
    User user;
    UserInfo userInfo;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public UserInfo getUserInfo() {
        return userInfo;
    }

    public void setUserInfo(UserInfo userInfo) {
        this.userInfo = userInfo;
    }

    public QueryVo(User user, UserInfo userInfo) {
        this.user = user;
        this.userInfo = userInfo;
    }

    public QueryVo() {
    }

    @Override
    public String toString() {
        return "QueryVo{" +
                "user=" + user +
                ", userInfo=" + userInfo +
                '}';
    }
}

好了,以上就是我举了一个实体类放两个实体类的映射方法了。User和UserInfo两个类,如果需要更多同理。而且他们对应的数据库是一对一关系,所以写配置文件映射时只用了标签,如果是多对多就先拆分为一对多,再使用标签进行映射就行了(现在想想确实比较麻烦,要建多个中间类,不如延迟加载)。