Mybatis建立一对一,一对多,多对多的关系

常用,上菜。

一、

1、一对一关系

例子:Person(人)类和Card(身份证)类

Person实体类:

 

private int pid;

private String pname;

 

private Card card;  //一对一  get、set....

 

Card实体类:

 

private int cid;

private String cnumber;      

 

 

2、然后,生成person.xml,这里我就把card.xml浓缩在person.xml里面去了:

<resultMap id="myPersonMap" type="com.desert.entity.Person">
    <id property="pid" column="pid"></id>
    <result property="pname" column="pname"></result>
    <association property="card" javaType="com.desert.entity.Card">
        <id property="cid" column="cid"></id>
        <result property="cnumber" column="cnumber"></result>
    </association>
</resultMap>

 

 

二、

1、一对多关系

例子:Provinces(省份)类和City(城市)类

Provinces 实体类:


private int pid;
private String pname;

private Set<City> citysSet;


City 实体类:


private int cid;
private String cname;
private int pid;

2、然后,生成Provinces.xml,这里我就把city.xml浓缩在Provinces .xml里面去了:

<resultMap id="myProvincesMap" type="com.desert.entity.Provinces">
    <id property="pid" column="pid"></id>
    <result property="pname" column="pname"></result>
    <collection property="citysSet" ofType="com.desert.entity.City">
        <id property="cid" column="cid"></id>
        <result property="cname" column="cname"></result>
        <result property="pid" column="pid"></result>
    </collection>
</resultMap>

 

 

三、

1、多对多关系

例子:Users(用户)类和Roles(角色)类

Users 实体类:

private int uid;
private String uname;

private Set<Roles> roles;

 
Roles 实体类:

 

private int rid;
private String rname;

private Set<Users> users;

2、然后,生成Users.xml:

<resultMap type="com.desert.entity.Users" id="usersMap">
        <id property="uid" column="uid" />
        <result property="uname" column="uname" />

    </resultMap>

    <resultMap type="com.desert.entity.Users" id="usersRolesMap" extends="usersMap">
        <collection property="roles" ofType="com.desert.entity.Roles">
            <id property="rid" column="rid" />
            <result property="rname" column="rname" />
        </collection>
    </resultMap>

然后,再生成Roles .xml:

<resultMap type="com.desert.entity.Roles" id="rolesMap">
        <id property="rid" column="rid" />
        <result property="rname" column="rname" />
    </resultMap>

    <resultMap type="com.desert.entity.Roles" id="rolesUsersMap" extends="rolesMap">
        <collection property="users" ofType="com.desert.entity.Users">
            <id property="uid" column="uid" />
            <result property="uname" column="uname" />
        </collection>
    </resultMap>

猜你喜欢

转载自blog.csdn.net/qq_35797735/article/details/85006547