1、 Defining entity classes , The code is as follows :

(1)、 Student entity :

package learn.jpa.entity;
import java.util.HashSet;
import java.util.Set; import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.JoinColumn; /**
* @doc Many to many relationships are equal , Think about deciding who is the maintenance section , Who is the protected segment
* Through the middle table ( In the middle of table ) To connect them
*/
@Entity
public class Student { private int id;
private String name;
private Set<Teacher> teacher = new HashSet<Teacher>(); public Student() {
super();
} public Student(String name) {
this.name = name;
} @Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(length=10,nullable=false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* inverseJoinColumns Foreign key associated with the maintained end
* joinColumns Foreign key associated with maintenance section
*/
@ManyToMany(cascade=CascadeType.REFRESH)
@JoinTable(name="student_teacher",inverseJoinColumns=@JoinColumn(name="teacher_id"),joinColumns=@JoinColumn(name="student_id"))
public Set<Teacher> getTeacher() {
return teacher;
}
public void setTeacher(Set<Teacher> teacher) {
this.teacher = teacher;
} // Build a relationship between teachers and students
public void addTeacher(Teacher teachers){
this.teacher.add(teachers);
} // Break the relationship between teachers and students
// Delete teacher It's based on id To delete , All in Teacher Class to override equals() and hashCode()
public void removeTeacher(Teacher teachers){
if(this.teacher.contains(teachers)){
this.teacher.remove(teachers);
}
}
}

(2)、 Teacher entity class :

package learn.jpa.entity;
import java.util.HashSet;
import java.util.Set; import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany; @Entity
public class Teacher { private int id;
private String name;
private Set<Student> student = new HashSet<Student>(); // If you declare a constructor with parameters , So be sure to declare a parameterless constructor
public Teacher(){} public Teacher(String name){
this.name = name;
} @Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(length=10,nullable=false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToMany(cascade=CascadeType.REFRESH,mappedBy="teacher")
public Set<Student> getStudent() {
return student;
}
public void setStudent(Set<Student> student) {
this.student = student;
} @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
} @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Teacher other = (Teacher) obj;
if (id != other.id)
return false;
return true;
} }

2、 Related operation class , The code is as follows :

package learn.jpa.test;
import static org.junit.Assert.*;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence; import learn.jpa.entity.Student;
import learn.jpa.entity.Teacher; import org.junit.Test; public class ManyToManyTest { /**
* Test whether the database can generate tables
*/
@Test
public void test() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("learn_jpa");
factory.close();
} @Test
public void save(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory("learn_jpa");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin(); // Open transaction
em.persist(new Student("xx"));
em.persist(new Teacher("xiuliu"));
em.getTransaction().commit();
em.close();
factory.close();
} /**
* Build a relationship between teachers and students ( Save the associated field data to the intermediate table )
*/
@Test
public void buildTS(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory("learn_jpa");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin(); // Open transaction
// In a hosted state , Data can be updated
Student student = em.find(Student.class, 1);
student.addTeacher(em.getReference(Teacher.class, 1));
em.getTransaction().commit();
em.close();
factory.close();
} // Break the relationship between teachers and students
@Test
public void deleteTS(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory("learn_jpa");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin(); // Open transaction
// In a hosted state , Data can be updated
Student student = em.find(Student.class, 1);
student.removeTeacher(em.getReference(Teacher.class, 1));
em.getTransaction().commit();
em.close();
factory.close();
} // Delete teacher
@Test
public void deleteTeacher(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory("learn_jpa");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin(); // Open transaction
// In a hosted state , Data can be updated
// Break the relationship between teachers and students first , In deleting the teacher
Student student = em.find(Student.class, 1);
Teacher teacher = em.getReference(Teacher.class, 1);
student.removeTeacher(teacher);
em.remove(teacher);
em.getTransaction().commit();
em.close();
factory.close();
} // Delete students
@Test
public void deleteStudent(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory("learn_jpa");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin(); // Open transaction
Student student = em.getReference(Student.class, 1);
em.remove(student);
em.getTransaction().commit();
em.close();
factory.close();
}
}

JPA Study --- Section 11 :JPA Many to many bidirectional associated entity definitions and annotation settings and operations in

  1. JPA One to many bidirectional association and cascade operation in

    Study Spring It's been two weeks , I feel that the server mainly realizes the maintenance of data relationship and the formulation of data structure , And what's generated by business needs CRUD , As long as the stable and efficient response to the interface provided by the front end is guaranteed , The specific front-end implementation doesn't care . ...

  2. Fengxuan safety WEB Safety learning lesson 21 Storage type XSS Explain

    Fengxuan safety WEB Safety learning lesson 21 Storage type XSS Explain Storage type XSS demonstration Storage type XSS, Persistence , The code is stored in the server , Such as in personal information or published articles, etc , Add code , If there is no filtration or filtration is not strict , So the code will be stored ...

  3. Hibernate From entry to mastery ( 11、 ... and ) Many to many bidirectional association mapping

    Last time we were in Hibernate From entry to mastery ( Ten ) Many to many one-way association mapping explains many to many one-way association mapping , This time, let's talk about the last of the seven kinds of maps, the many to many bidirectional associative mapping . Many to many bidirectional association mapping According to our previous practice , Let's take a look at ...

  4. Hibernate( 11、 ... and ) Many to many bidirectional association mapping

    Last time we were in Hibernate From entry to mastery ( Ten ) Many to many one-way association mapping explains many to many one-way association mapping , This time I Let's talk about the last of the seven kinds of maps, the many to many bidirectional associative mapping . Many to many bidirectional association mapping According to our previous practice , First look at ...

  5. [ Roof placement ] Hibernate From entry to mastery ( 11、 ... and ) Many to many bidirectional association mapping

    Last time we were in Hibernate From entry to mastery ( Ten ) Many to many one-way association mapping explains many to many one-way association mapping , This time, let's talk about the last of the seven kinds of maps, the many to many bidirectional associative mapping . Many to many bidirectional association mapping According to our previous practice , Let's take a look at ...

  6. Mybatis Use in collection Examples of many to many bidirectional association ( contain XML Version and annotation version )

    Mybatis Use in collection Examples of many to many bidirectional association ( contain XML Version and annotation version ) XML edition : Entity class : @Data @NoArgsConstructor public class Course ...

  7. JPA Study --- Section 9 :JPA One to many bidirectional association and cascade operation in

    One . One to many bidirectional association and cascade operation 1. Create project , The configuration file code is as follows : <?xml version="1.0" encoding="UTF-8"?> < ...

  8. JPA Study --- Section 10 :JPA One to one two-way Association in

    1. Create entity class , The code is as follows : Code list 1: package learn.jpa.entity; import javax.persistence.CascadeType; import javax.pe ...

  9. JPA Study --- Section 5 : Field types such as date and enumeration JPA mapping

    1. In the previous section, you can see the created tables and fields in the database , It's through Entity bean To create , What are the rules for creating table names and field names ? Some kind , The code is as follows : package learn.jpa.bean; impo ...

Random recommendation

  1. PHP Get current location

    If you want to dynamically get the position of the current column , It's going to be related to the database , Here is an example : Column table (category): It's about the secondary directory . (1) First, in your home page navigation bar , There are also links on the home page , Add... To the column catid, Just like this. ...

  2. 【python】pandas &amp; matplotlib Data processing Draw the surface

    Python matplotlib modular , It's expanded MATLAB A drawing tool library for , It can draw all kinds of graphics Proposed installation Anaconda After use , Integrated with a lot of third Libraries , Basically meet everyone's needs , Download address , Corresponding selection pytho ...

  3. 【BZOJ】2435: [Noi2011] Road construction ( Tree form dp)

    http://www.lydsy.com/JudgeOnline/problem.php?id=2435 How do I feel so water .. The pit is ,dfs Explosive ... ok .. use bfs.. //upd: My IQ is drunk, too ...

  4. Go to xml Update nodes in

    /* System.out.println("2323"); DocumentBuilderFactory factory = DocumentBuilderFactory.new ...

  5. JAX-WS + Spring Development webservice

    Through a few days of study under the use of jax-ws To develop webservice, After reading some information on the Internet, I come to the conclusion that jax-ws There are two kinds of development . The following items use spring3.0,jar The package can be downloaded from the official website The first one is : Use independent ...

  6. android Interview listview

    ListView Optimization has always been a platitude , Whether it's an interview or normal development ,ListView It will never be ignored , So in this article, let's look at how to maximize the optimization ListView Performance of .· 1. stay adapter Medium g ...

  7. mvn -DskipTests and -Dmaven.test.skip=true difference

    In the use of mvn package Compile . When the packaging ,Maven Will execute src/test/java Medium JUnit The test case , Sometimes in order to skip the test , Will use parameters -DskipTests and -Dmaven.test.skip= ...

  8. Redis introduction --- String type

    Read the directory 1.keys * command 2. Determine if a bond exists (exists key) 3. Delete key 4. Get the data type of the key value 5 Increasing numbers (incr) 6. Increase the specified integer (INCRBY) 7. Reduce the specified integer ...

  9. 【 Algorithm 】LeetCode Algorithm problem -Roman To Integer

    This is the number one of Yuele book 145 Secondary update , The first 147 Original article Today's question is about Roman numbers , Roman numerals can also represent integers , Such as "I" Representation number 1,"IV" Representation number 4, The following topic is similar to Roman number ...

  10. Simple and easy RPC frame -SPI

    *:first-child { margin-top: 0 !important; } body > *:last-child { margin-bottom: 0 !important; } ...