Hibernate-----一对多关联映射(注解)

双向1-N:一般在‘一’的一端用mappedBy属性反转;把维护端交给‘多’的一端

 

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定义在Classes中,Classes类将不负责维护级联关系.维护者交由Student.所以
    // 1.要将Clsses的数据,赋给Student(用Student的setClasses()方法去捆定class数据)
    // 2.在进行数据插入/更新时,最后操作的是Student(维护端)
    @OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY, mappedBy = "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;
    }
 
    // 多个cascade:{CascadeType.PERSIST,CascadeType.MERGE}
    // 在多的一端指定外键(class_id)
    @ManyToOne(cascade = { CascadeType.ALL })
    @JoinColumn(name = "class_id")
    public Classes getClasses() {
       return classes;
    }
 
    public void setClasses(Classes classes) {
       this.classes = classes;
    }
}


 

因为一端维护关系另一端不维护关系的原因,必须注意避免在应用中用不维护关系的类(class)建立关系,因为这样建立的关系是不会在数据库中存储的(应先保存非维护端,最后保存维护端)




郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。