Hibernate and hibernate

Source: Internet
Author: User

Hibernate and hibernate
In this example, the relationship between students and teachers is a typical multi-to-many relationship. A teacher can have multiple students, A student can have multiple teachers. A student table is required to store student information in the database, and a teacher table is used to store teacher information. To express the relationship between them, an intermediate table is required to indicate the relationship between them.

For example, the instructor table has two attributes: id and name. The student table also has two attributes: id and name. The instructor table has two records: (1, Instructor Dong), (2, instructor Li), and the student table also has two records (1, John 3), (2, Lee 4 ). In the middle table, there are two fields (teacherId, studentId), which constitute a joint primary key, and these two fields are also foreign keys of the instructor table and student table, when teachers and students are associated, the IDs of the associated teachers and students can be directly inserted in the middle table. For example, inserting () in the middle table means that the teachers and students are associated, insert (1, 2) to indicate that Instructor Dong is associated with Mr. Li.

Let's take a look at the Teacher Class and Student class.

package entity;import java.util.HashSet;import java.util.Set;public class Teacher {private Long id;private String name;private Set<Student> students = new HashSet<Student>();public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Set<Student> getStudents() {return students;}public void setStudents(Set<Student> students) {this.students = students;}}
package entity;import java.util.HashSet;import java.util.Set;public class Student {private Long id;private String name;private Set<Teacher> teachers = new HashSet<Teacher>();public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Set<Teacher> getTeachers() {return teachers;}public void setTeachers(Set<Teacher> teachers) {this.teachers = teachers;}}

The POJO class still uses a set to indicate that multiple records exist.

The following shows a ing configuration file.

First, let's look at Teacher. hbm. xml.

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE hibernate-mapping PUBLIC "-// Hibernate/Hibernate DTD ing DTD 3.0 // EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

The <Set> label is still used in the ing configuration file for the set type attribute in the class, in the <set> label, use <sequence-to-sequence> to indicate that the relationship between them is many-to-many.

Then read Student. hbm. xml.

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE hibernate-mapping PUBLIC "-// Hibernate/Hibernate DTD ing DTD 3.0 // EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

In this way, the multi-to-Multi-Association ing between teachers and students is configured. Let's take a look at the test class. Here we use JUtil for testing

Package test; import static org. junit. assert. *; import java. util. iterator; import java. util. set; import org. hibernate. session; import org. hibernate. transaction; import entity. student; import entity. teacher; import factory. hibernateSessionFactory; public class Test {private Session session = null; private Transaction tran = null; // storage object @ org. junit. testpublic void save () {session = HibernateSessionFactory. getSession (); tran = session. beginTransaction (); try {Teacher teacher = new Teacher (); teacher. setId (1L); teacher. setName ("Instructor Dong"); Teacher t2 = new Teacher (); t2.setId (2l); t2.setName ("instructor Li"); Student s1 = new Student (); s1.setId (1L); s1.setName (""); Student s2 = new Student (); s2.setId (2l); s2.setName ("James"); teacher. getStudents (). add (s1); teacher. getStudents (). add (s2); t2.getStudents (). add (s1); t2.getStudents (). add (s2); s1.getTeachers (). add (teacher); s1.getTeachers (). add (t2); s2.getTeachers (). add (teacher); s2.getTeachers (). add (t2); session. save (teacher); session. save (t2); session. save (s1); session. save (s2); tran. commit ();} catch (Exception e) {tran. rollback () ;}// obtain the instructor information @ org. junit. testpublic void GetTeacher () {session = HibernateSessionFactory. getSession (); tran = session. beginTransaction (); try {Teacher teacher = (Teacher) session. get (Teacher. class, 1l); Set <Student> set = teacher. getStudents (); System. out. println (teacher. getName () + "Student:"); Iterator <Student> it = set. iterator (); while (it. hasNext () {Student s = it. next (); System. out. println (s. getName ();} tran. commit ();} catch (Exception e) {tran. rollback () ;}// unassociate @ org. junit. testpublic void RemoveRelation () {session = HibernateSessionFactory. getSession (); tran = session. beginTransaction (); try {Student s = (Student) session. get (Student. class, 1l); Teacher teacher = (Teacher) session. get (Teacher. class, 1l); // If the inverse attribute of Teacher is false, it can be removed. If it is true, it cannot be removed. getStudents (). remove (s); tran. commit ();} catch (Exception e) {tran. rollback () ;}// Delete Association @ org. junit. testpublic void DeleteRelation () {session = HibernateSessionFactory. getSession (); tran = session. beginTransaction (); try {Teacher teacher = (Teacher) session. get (Teacher. class, 2l); // when the inverse attribute of teacher is false, the instructor information can be deleted, delete related records in the intermediate table // when the inverse attribute is true, an exception session is thrown when the instructor information is deleted. delete (teacher); tran. commit ();} catch (Exception e) {tran. rollback ();}}}


 


What is the difference between one-to-multiple mappings between one-way associations and two-way mappings in hibernate?

<One-to-one association> one-way Association is to maintain the relationship only unilaterally. Two-way Association is to maintain the relationship on both sides, and to determine whether one-way Association is used or two-way Association, it depends on your business requirements. If one-way contact can meet the business requirements you need, it must be one-way Association. (My suggestion is to use one-way Association, using Bidirectional Association makes the relationship complex and prone to problems ). The Association also involves the issue of control. in <one-to-many>, it is best to give control to the other party (who is responsible for maintaining the relationship between them ),

Hibernate multiple-to-multiple ing a complex intermediate table using the combined primary key

For example:
Multi-to-many bidirectional Association
Relationship example: Teachers <--> students, teachers need to know which students they have taught, and students also know which teachers they have.
Database: Intermediate table
Annotation: @ manytoation
XML: <relative-to-sequence>
For multi-to-multiple unidirectional configuration, you only need to configure one end. For bidirectional configuration, You need to configure both ends.
Relationship Model (Teache many-to-many Student)
Multiple Teacher (id, name, students)
Set <Student> students = new HashSet <Student> ()

Student (id, name, teachers) Many
Set <Teacher> teachers = new HashSet <Teacher> ();

Annotation Configuration
Configure students at the end of the Teacher
// If you manually specify the table name and field name of the generated intermediate table
@ Manytoyun
@ JoinTable (name = "t_s ",
JoinColumns ={@ JoinColumn (name = "teacher_id ")},
InverseJoinColumns ={@ JoinColumn (name = "student_id ")}
)
The teachers at the Student end only needs to be configured
@ Manytots (mappedBy = "students ")

XML configuration method: the configuration is the same at both ends. Note that the table name and the field attribute names of the generated intermediate table must be consistent.
Teacher end Configuration
<Set name = "students" table = "t_s">
<Key column = "teacher_id"/>
<Example-to-learn class = "com. xxx. Student" column = "student_id"/>
</Set>
Configure at the end of Student
<Set name = "teachers" table = "t_s">
<Key column = "student_id"> </key>
<Your-to-register class = "com. xxx. Teacher" column = "teacher_id"/>
</Set>
The generated table is
Create table Student (
Id integer not null auto_increment,
Name varchar (255 ),
Primary key (id)
)
Create table Teacher (
Id integer not null auto_increment,
Name varchar (255 ),
Primary key (id)
)
Create table t_s (// generated intermediate table
Teacher_id integer not null,
Student_id ...... remaining full text>

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.