Hibernate关系映射多对多

来源:互联网 发布:开淘宝店怎么样 编辑:程序博客网 时间:2024/05/23 17:01

多对多:

单向注解:

@ManyToMany(cascade={javax.persistence.CascadeType.ALL})@JoinTable(name="teacher_student",joinColumns=@JoinColumn(name="tid"),inverseJoinColumns=@JoinColumn(name="sid"))public Set<Student> getStudents() {return students;}

单向XML:

<class name="Person"><id name="id" column="personId"><generator class="native" /></id></class><class name="Address"><id name="id" column="addressId"><generator class="native" /></id><set name="persons" table="PersonAddress"><key column="addressId" /><many-to-many column="personId" class="Person" /></set></class>

create table Person ( personId bigint not null primary key )create table PersonAddress ( personId bigint not null, addressId bigint not null, primary key (personId, addressId) )create table Address ( addressId bigint not null primary key )

注解双向:

@ManyToMany(cascade={javax.persistence.CascadeType.ALL})@JoinTable(name="teacher_student",joinColumns=@JoinColumn(name="tid"),inverseJoinColumns=@JoinColumn(name="sid"))public Set<Student> getStudents() {return students;}

@ManyToMany(mappedBy="students")public Set<Teacher> getTeachers() {return teachers;}

XML双向:

<class name="Person">    <id name="id" column="personId">        <generator class="native"/>    </id>    <set name="addresses" table="PersonAddress">        <key column="personId"/>        <many-to-many column="addressId"            class="Address"/>    </set></class><class name="Address">    <id name="id" column="addressId">        <generator class="native"/>    </id>    <set name="people" inverse="true" table="PersonAddress">        <key column="addressId"/>        <many-to-many column="personId"            class="Person"/>    </set></class>

create table Person ( personId bigint not null primary key )create table PersonAddress ( personId bigint not null, addressId bigint not null, primary key (personId, addressId) )create table Address ( addressId bigint not null primary key )


ps.若不添加事务,或者开始了事务但是没有commit,会使得中间表没有数据。


原创粉丝点击