码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2014-11-29 13:18:47      阅读:263      评论:0      收藏:0      [点我收藏+]

标签: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)建立关系,因为这样建立的关系是不会在数据库中存储的(应先保存非维护端,最后保存维护端)




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

标签:hibernate   注解   一对多   多对一   关联映射   

原文地址:http://blog.csdn.net/hekewangzi/article/details/41594493

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!