A comprehensive application of "hibernate" in relation mapping
1. How Association mappings handle business logic
2. How to specify the intermediate table
3, how to cascade operation
4. How to solve the problem of primary key confusion in the process of hibenrate building table
Now there are three tables
Student (student table), Course (curriculum), score (student, course, score, table)
So our analysis of business logic shows that students and courses are many-to-many relationships, students and score tables are a one-to-many relationship, and courses and scores are also a one -to-many relationship .
look directly at the annotations configuration, All my configurations here are two-way associations, so in fractions, courses, students, among them, you can find each other at will!
@Entity @table (name= "C_course") public class Course {private Integer ID; Private String Coursename; Private set<student> students=new hashset<student> (); Private set<score> scores=new hashset<score> (); @OneToMany (mappedby= "course")//must specify that the relationship is maintained by more than one party public set<score> Getscores () {return scores; } public void Setscores (set<score> scores) {this.scores = scores; } @ManyToMany//Specifies that the intermediate table is S_score @JoinTable (name= "S_score", joincolumns={@JoinColumn (name= "course_id")}, Inver sejoincolumns={@JoinColumn (name= "student_id")}) public set<student> getstudents () {return students; } public void Setstudents (set<student> students) {this.students = students; } @Id @GeneratedValue public Integer getId () {return Id; } public void SetId (Integer id) {this.id = ID; } @Column (name= "C_coursename") public String Getcoursename () {return Coursename; } public void Setcoursename (String coursename) {this.coursename = Coursename; }}
(curriculum course)
@Entity @table (name= "t_student") public class Student {private Integer ID; private String name; Private set<course> courses=new hashset<course> (); Private set<score> scores=new hashset<score> (); @OneToMany (mappedby= "student") public set<score> Getscores () {return scores; } public void Setscores (set<score> scores) {this.scores = scores; } @ManyToMany @JoinTable (name= "S_score", joincolumns={@JoinColumn (name= "student_id")}, inversejoincolumns= {@JoinColumn (name= "course_id")}) Public set<course> getcourses () {return courses; } public void Setcourses (set<course> courses) {this.courses = courses; } @Id @GeneratedValue public Integer getId () {return Id; } public void SetId (Integer id) {this.id = ID; } @Column (name= "S_name") public String GetName () {return name; } public void SetName (String name) { THIS.name = name; } }
(Student student table)
@Entity @table (name= "S_score") public class score {private Integer ID; Private String score; Private Student Student; Private Course Course; @ManyToOne (Cascade={cascadetype.all})//Configure cascading Operations @JoinColumn (name= "student_id") public student Getstudent () {RE Turn student; } public void Setstudent (Student Student) {this.student = Student; } @ManyToOne (Cascade={cascadetype.all}) @JoinColumn (name= "course_id") Public course GetCourse () {return C Ourse; } public void Setcourse (Course Course) {this.course = Course; } @Id @GeneratedValue public Integer getId () {return Id; } public void SetId (Integer id) {this.id = ID; } @Column (name= "S_score") public String Getscore () {return score; } public void SetScore (String score) {This.score = score; } }
(Table of tables, also intermediate correlations, score)
So here's the problem, using hibernate to automatically build the table, let's look at the build statement
12:11:08,169 DEBUG schemaexport:415- CREATE TABLE c_course ( ID integer NOT NULL auto_increment, c_ Coursename varchar (255), primary key (ID) ) 12:11:08,333 DEBUG schemaexport:415- CREATE TABLE S_score ( ID integer NOT NULL, s_score varchar (255), course_id Integer, student_id integer NOT null auto_ Increment, primary key (student_id, course_id) ) 12:11:08,455 DEBUG schemaexport:415- CREATE TABLE T_ Student ( ID integer NOT NULL auto_increment, s_name varchar (255), primary key (ID) )
We found that the table is hibernate by default student_id and course_id are used as primary keys, and student_id or self-increment
This is obviously wrong, here I also really think, good way, smart use a stupid way, manually change back!
It is best to use tools, because, if you create directly, student_id and course_id are not associated with Student,course's primary key ID.
OK, here, our build table is basically complete, below junittest
@Test public void Add () {try {configuration cfg=new configuration (); Cfg.configure (); Sessionfactory sessionfactory=cfg.buildsessionfactory (); Session session=sessionfactory.opensession (); Session.begintransaction (); Student student1=new Student (); Student1.setname ("Zhang 31");//Student student2=new Student ();//Student2.setname ("John Doe"); Course c1=new Course (); C1.setcoursename ("Mathematics 1"); Course c2=new Course (); C2.setcoursename ("Language 1");//Session.save (STUDENT1);//Session.save (C1);//Session.save (STUDENT2) ;//Session.save (C2); Score Score=new score (); Score.setscore ("901"); Score.setcourse (C1); Score.setstudent (STUDENT1); Zhang San Mathematics 90 cent Session.save (score); Score Score2=new score (); Score2.setcourse (C2); Score2.setScore ("100"); Score2.setstudent (STUDENT1); Session.save (Score2); Session.gettransaction (). commit (); Session.close (); Sessionfactory.close (); } catch (Hibernateexception e) {e.printstacktrace (); } }
OK, as you can see, why do we only need to save score at the end of the line? Why is it possible to save the database directly without Session.save () student and course? This is
Cascade={cascadetype.all}
Cascade operation, of course, I configured here is all, in fact, there are 4 parameters, we can study slowly!
Add the above success, then we directly load test;
public void Findtest () { configuration cfg=new configuration (); Cfg.configure (); Sessionfactory sessionfactory=cfg.buildsessionfactory (); Session s=sessionfactory.opensession (); S.begintransaction (); Student student= (Student) s.load (Student.class, 2); System.out.println ("Student Name" +student.getname ()); For (Course course:student.getCourses ()) { System.out.print ("--------" + "Course Name" +course.getcoursename ()); For (score Score:course.getScores ()) { System.out.println ("--------" + "Course Score" +score.getscore ()); } } S.gettransaction (). commit (); S.close (); Sessionfactory.close (); }
It's okay.
update?
public void Update () { configuration cfg=new configuration (); Cfg.configure (); Sessionfactory sessionfactory=cfg.buildsessionfactory (); Session s=sessionfactory.opensession (); S.begintransaction (); Student student= (Student) s.load (student.class,1); We will now change the language score to 0 points for (Course course:student.getCourses ()) { System.out.println (Course.getcoursename () ); if ("Language". Equals (Course.getcoursename ())) {for (score score:course.getScores ()) { if (score.getstudent ()). GetId (). Equals (Student.getid ())) { Score.setscore ("0"); S.update (score); }}} S.gettransaction (). commit (); S.close (); Sessionfactory.close (); }
Delete?
@Test public void Deleteobj () { configuration cfg=new configuration (); Cfg.configure (); Sessionfactory sessionfactory=cfg.buildsessionfactory (); Session s=sessionfactory.opensession (); S.begintransaction (); Student student= (Student) s.load (student.class,3); S.delete (student); S.gettransaction (). commit (); S.close (); Sessionfactory.close (); }
OK, here basically, complete the basic operation of Hibernate association mapping!
Note that when many-to-many deletions, we generally delete the intermediate table data? But often because of the foreign Key Association, hibernate removes the data from the other table to disassociate the relationship, which is wrong! Follow up and explore!
Delete?
A comprehensive application of hibernate in relation mapping