bidirectional 1-n : Usually at the end of the ' one ' Mappedby attribute reversal; give the maintenance end to ' many '
One
Import Javax.persistence.cascadetype;import Javax.persistence.column;import Javax.persistence.entity;import Javax.persistence.generatedvalue;import Javax.persistence.generationtype;import Javax.persistence.Id;import Javax.persistence.onetomany;import javax.persistence.Table; @Entity @table (name = "T_classes") public class classes Implements Serializable {private int id; private String name; Private set<student> students; @Id @GeneratedValue (strategy = generationtype.auto) public int getId () {return Id; } public void setId (int id) {this.id = ID; } @Column (name = "name") public String GetName () {return name; } public void SetName (String name) {this.name = name; }//Mappedby defined in classes, the classes class will not be responsible for maintaining a cascading relationship. The maintainer is handed over to student. So//1. To assign clsses data to student (student with setclasses () method to bind the class data)//2. When data insertion/update is performed, the last operation is the student (Maintenance side) @OneToMany (cascade = cascadetype.remove, fetch = Fetchtype.lazy, M Appedby = "Classes") Public set<student> getstudents () {return students; } public void Setstudents (set<student> students) {this.students = students; }}
Many
Import Javax.persistence.joincolumn;import Javax.persistence.ManyToOne; @Entity @table (name = "T_student") public Class Student implements Serializable { private int sid; Private String sname; Private Classes Classes; @Id @GeneratedValue (strategy = generationtype.auto) public int GetSID () { return sid; } public void Setsid (int sid) { this.sid = sid; } @Column (name = "sname") public String Getsname () { return sname; } public void Setsname (String sname) { this.sname = sname; } Multiple Cascade:{cascadetype.persist,cascadetype.merge} //Specifies the foreign key (class_id) @ManyToOne at one end of the many (cascade = { Cascadetype.all}) @JoinColumn (name = "class_id") public Classes getclasses () { return Classes; } Public void Setclasses (Classes Classes) { this.classes = Classes; }}
because one end maintains the reason why relationships are not maintained at the other end, it is important to avoid using classes that do not maintain relationships in your application . (Class) relationships are established because the relationships are not stored in the database (the non-maintenance side should be saved first, and the maintenance end should be saved)
Hibernate-----One-to-many association mappings (annotations)