017 多对多关联映射 双向(many-to-many)

时间:2021-11-08 19:12:09

多对多关联映射 双向 两方都持有对象引用,修改对象模型,但数据的存储没有变化。

再修改映射文件:

public class Role {

    private int id;

    private String name;

private Set users;//users对象的集合

    public int getUsers() {

        return users;

    }

    public void setUsers(int users) {

        this.users= users;

    }

    public int getId() {

        return id;

    }

    public void setId(int id) {

        this.id = id;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

}

Role映射文件:

<hibernate-mapping>

    <class name="com.wjt276.hibernate.Role" table="t_role">

        <id name="id">

            <generator class="native"/>

        </id>

        <property name="name" column="name"/>

        <!— order-by 属性是第三方表哪个字段进行排序-->

        <set name="users" table="t_user_role" order-by="userid">

            <key column="roleid"/>

            <many-to-many class="com.wjt276.hibernate.User" column="userid"/>

        </set>

    </class>

</hibernate-mapping>

注:数据的存储与单向一样。但一般维护这个多对多关系,只需要使用一方,而使另一方维护关系失效。

多对多关联映射双向数据加载

       session = HibernateUtils.getSession();

            tx = session.beginTransaction();

            Role role = (Role)session.load(Role.class, 1);

            System.out.println("role.name=" + role.getName());

            for (Iterator<User> iter = role.getUsers().iterator();iter.hasNext();){

                User user = iter.next();

                System.out.println("user.name=" + user.getName());

            }

            //提交事务

            tx.commit();

生成SQL语句:

Hibernate: select role0_.id as id2_0_, role0_.name as name2_0_ from t_role role0_ where role0_.id=?

role.name=数据录入人员

Hibernate: select users0_.roleid as roleid1_, users0_.userid as userid1_, user1_.id as id0_0_, user1_.name as name0_0_ from t_user_role users0_ left outer join t_user user1_ on users0_.userid=user1_.id where users0_.roleid=? order by users0_.userid

user.name=10

user.name=成龙

总结:

<!— order-by 属性是第三方表哪个字段进行排序-->

        <set name="users" table="t_user_role" order-by="userid">

            <key column="roleid"/>

            <many-to-many class="com.wjt276.hibernate.User" column="userid"/>

        </set>
  • table属性值必须和单向关联中的table属性值一致
  • <key>column属性值要与单向关联中的<many-to-many>标签中的column属性值一致
  • <many-to-many>中的column属性值要与单向关联中<key>标签的column属性值一致。