Hibernate association mapping
Keywords:
Session
1.1 many to many relationship
1.1.1 use annotations to complete many to many configuration.
To configure many to many, you only need to configure the intermediate table on one side and use mappedby on the other side to represent foreign key maintenance.
A. Create PO class
In the Teacher class:
@Entity
@Table(name="t_teacher")
public class Teacher {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
@ManyToMany(targetEntity = Student.class,mappedBy="teacher") / / indicates that the foreign key is maintained by the opposite party
private Set<Student> students = new HashSet<Student>();
Student Class:
@Entity
@Table(name = "t_student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
@ManyToMany(targetEntity = Teacher.class)
@JoinTable(name="s_t",joinColumns={@JoinColumn(name="c_student_id")},inverseJoinColumns={@JoinColumn(name="c_teacher_id")})
private Set<Teacher> students = new HashSet<Teacher>();
// Test multi-to-multi-level joint saving, save teacher when saving students
@Test
public void test4(){
Session session = hibernateUtils.openSession()
session.beginTransaction()
// Create two teachers
Teacher t1 = new Teacher()
t1.setName("tommy")
Teacher t2 = new Teacher()
t2.setName("hans")
// Create two students
Student s1 = new Student()
s1.setName("tommy2")
Student s2 = new Student()
s2.setName("hans2")
// Students relate to teachers
s1.getTeacher().add(t1)
s1.getTeacher().add(t2)
s2.getTeacher().add(t1)
s2.getTeacher().add(t2)
// Save students
session.save(s1)
session.save(s2)
session.getTransaction().commit()
session.close()
}
Problem: if we establish cascading deletion in many to many.
What happens if we delete tommy?
--All the cascading data is gone.
2. One to one relationship
Take person and ID card number as an example
1. Create entity class
Posted by dirtyfrenchman on Thu, 02 Apr 2020 22:47:40 -0700