Jpa Bidirectional Multi-to-Multi-relationship, jpa Bidirectional Multi-to-Relationship

Source: Internet
Author: User

Jpa Bidirectional Multi-to-Multi-relationship, jpa Bidirectional Multi-to-Relationship

Compared with other associations, many-to-many relationships are a little more complex. This complexity is mainly reflected in the understanding of such associations. Different from other associations, this association has an intermediate table, and the operation is a little more complicated. Let's take a look.

1. entity definition

Student table:

package org.lxh.info;import java.util.*;import javax.persistence.CascadeType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.JoinTable;import javax.persistence.ManyToMany;@Entitypublic class Student {private Integer id;private String name;private Set<Teacher> teachers;@Id@GeneratedValuepublic Integer getId() {return id;}public void setId(Integer id) {this.id = id;}@Column(length = 50)public String getName() {return name;}public void setName(String name) {this.name = name;}@ManyToMany(cascade=CascadeType.REFRESH)@JoinTable(name="student_teacher",inverseJoinColumns=@JoinColumn(name="teacherId"),joinColumns=@JoinColumn(name="stuId"))public Set<Teacher> getTeachers() {return teachers;}public void setTeachers(Set<Teacher> teachers) {this.teachers = teachers;}}

@ ManyToMany indicates multiple-to-multiple associations. In rare cases, cascade deletion is used. Here I set cascade refresh; because an intermediate table exists, @ JoinTable is used to set the name after the joined table. inverseJoinColumn is used to configure the intermediate table field corresponding to the primary key of the maintained link, joinColumn is configured with the intermediate table field corresponding to the primary key of The Link maintainer. This is the most complicated part.


Teacher table:

package org.lxh.info;import java.util.*;import javax.persistence.CascadeType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.ManyToMany;@Entitypublic class Teacher {private Integer id;private String name;private Set<Student> students;       @Id @GeneratedValuepublic Integer getId() {return id;}public void setId(Integer id) {this.id = id;}        @Column(length=50)public String getName() {return name;}public void setName(String name) {this.name = name;}        @ManyToMany(cascade=CascadeType.REFRESH,mappedBy="teachers")public Set<Student> getStudents() {return students;}public void setStudents(Set<Student> students) {this.students = students;}}

The object is defined here. Note that only the link maintenance party can update the foreign key records in the intermediate table. Otherwise, an error is reported.


2 multiple-to-Multiple Data Storage

/*** Bidirectional multiple-to-multiple save */@ org. junit. testpublic void testMany2ManyInsert () {EntityManager em = null; EntityTransaction tx = null; try {em = JpaUtil. getEntityManager (); tx = em. getTransaction (); tx. begin (); Student s = new Student (); s. setName ("Zhang Xiaohua"); Student s2 = new Student (); s2.setName ("Chen Xiaoming"); Set <Student> students = new HashSet <Student> (); students. add (s); students. add (s2); Teacher t = new Teacher (); t. setName ("instructor Li"); t. setStudents (st Udents); Teacher t2 = new Teacher (); t2.setName (""); t2.setStudents (students); Set <Teacher> teachers = new HashSet <Teacher> (); teachers. add (t); teachers. add (t2); s. setTeachers (teachers); s2.setTeachers (teachers); em. persist (s); em. persist (s2); em. persist (t); em. persist (t2); tx. commit ();} catch (Exception e) {e. printStackTrace ();} finally {if (em! = Null) {em. close ();}}}
The Save operation is relatively simple, but if you want to delete or remove the association, it is a little complicated. Let's look at this code.

@ Org. junit. testpublic void testMany2ManyDelete () {EntityManager em = null; EntityTransaction tx = null; try {em = JpaUtil. getEntityManager (); tx = em. getTransaction (); tx. begin (); Student s = em. find (Student. class, 1); Student s2 = em. find (Student. class, 2); Teacher t = em. find (Teacher. class, 2); // first disassociate s. getTeachers (). remove (t); s2.getTeachers (). remove (t); // The data can be deleted through the maintenance end after the link is unbound. remove (t); tx. commit ();} catch (effectio N e) {e. printStackTrace ();} finally {if (em! = Null) {em. close ();}}}

At last, we will summarize the key points for using associations: clarify the relationship maintenance end and the link maintenance end, reasonable use notes, and cascade settings based on the specific situation.


JPA one-to-multiple bidirectional association query

Add fetch = FetchType. EAGER after cascade = CascadeTpe. ALL to actively capture ing classes.

How to configure multiple-to-multiple relationship bidirectional for Hibernate

Users Pojo:
Public Set popedom = new HashSet ();

Public Set getPopedom (){
Return popedom;
}

Public void setPopedom (Set popedom ){
This. popedom = popedom;
}
Users ing file:
<Set name = "Popedom" table = "Users_Popedom">
<Key column = "UsersId"/>
<Your-to-register class = "com. seipher. pojo. systemSet. Popedom" column = "PopedomId"/>
</Set>
==========================================================
Pojo of Popedom:
Public Set UsersManage = new HashSet ();

Public Set getUsersManage (){
Return UsersManage;
}

Public void setUsersManage (Set usersManage ){
UsersManage = usersManage;
}

Popedom ing file:
<Set name = "UsersManage" table = "Users_Popedom">
<Key column = "PopedomId"/>
<Role-to-register class = "com. seipher. pojo. systemSet. UsersManage" column = "UsersId"/>
</Set>

These two are not the many-to-many bidirectional relationship of hibernate? Many-to-many, and two-way supervision.

Code operation:
/**
* Add permissions to users, that is, the relationship between users and permissions.
*
* @ Param yhxxid
* @ Param xtqxid
*/
Public void setPopedom (String yhxxid, String [] xtqxid) throws HibernateException {
Session = HibernateSession. hdSession ();
UsersManage usersManage = (UsersManage) this. load (yhxxid );
UsersManage. getPopedom (). clear ();
List result = new ArrayList ();
For (int I = 0; I <xtqxid. length; I ++ ){
... The remaining full text>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.