hibernate annotation 之 一对多、多对一双向外键关联

作者: storm king
发布时间:2015-08-07 10:41:46

假设,一个农场产出多种植物,具体的某一植物产于某一农场。

  3 import java.io.Serializable;
  4 import java.util.Set;
  5 import javax.persistence.CascadeType;
  6 import javax.persistence.Column;
  7 import javax.persistence.Entity;
  8 import javax.persistence.FetchType;
  9 import javax.persistence.GeneratedValue;
 10 import javax.persistence.Id;
 11 import javax.persistence.OneToMany;
 12 /**
 13  * -----------------------------------------
 14  * @描述  农场
 17  * @日期  2012-10-21 <p>
 18  * -----------------------------------------
 19  */
 20 @Entity
 21 public class Farm implements Serializable{
 22
 23     private static final long serialVersionUID = 1L;
 24    
 25     private Integer id;
 26     private String  name;
 27     private Set<Plant> plantSet;
 28    
 29     @Id
 30     @GeneratedValue
 31     public Integer getId() {
 32         return id;
 33     }
 34     @Column(length = 18, nullable = false)
 35     public String getName() {
 36         return name;
 37     }
 38     @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "farm")
 39     public Set<Plant> getPlantSet() {
 40         return plantSet;
 41     }
 42     public void setId(Integer id) {
 43         this.id = id;
 44     }
 45     public void setName(String name) {
 46         this.name = name;
 47     }
 48     public void setPlantSet(Set<Plant> plantSet) {
 49         this.plantSet = plantSet;
 50     }
 51 }
3 import java.io.Serializable;
  4 import javax.persistence.CascadeType;
  5 import javax.persistence.Column;
  6 import javax.persistence.Entity;
  7 import javax.persistence.FetchType;
  8 import javax.persistence.GeneratedValue;
  9 import javax.persistence.Id;
 10 import javax.persistence.ManyToOne;
 11 /**
 12  * -----------------------------------------
 13  * @描述  植物
 16  * @日期  2012-10-21 <p>
 17  * -----------------------------------------
 18  */
 19 @Entity
 20 public class Plant implements Serializable{
 21
 22     private static final long serialVersionUID = 1L;
 23    
 24     private Integer id;
 25     private String   name;
 26     private Farm    farm;
 27    
 28     @Id
 29     @GeneratedValue
 30     public Integer getId() {
 31         return id;
 32     }
 33     @Column(length = 18, nullable = false)
 34     public String getName() {
 35         return name;
 36     }
 37     @ManyToOne(cascade = CascadeType.PERSIST, optional = false, fetch = FetchType.LAZY)
 38     public Farm getFarm() {
 39         return farm;
 40     }
 41     public void setId(Integer id) {
 42         this.id = id;
 43     }
 44     public void setName(String name) {
 45         this.name = name;
 46     }
 47     public void setFarm(Farm farm) {
 48         this.farm = farm;
 49     }
 50
 51 }

 

标签: Hibernate
来源:http://www.cnblogs.com/panxueji/p/3163480.html

推荐: