码迷,mamicode.com
首页 > 其他好文 > 详细

注解(annotaion)一对一、一对多、多对一

时间:2015-08-18 13:53:15      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

一对一单向[oneToOne] 

  

public class User {

   private Group group;

   @OneToOne(cascade=CascadeType.ALL)     

   @JoinColumn(name="GROUP_ID")     

   public Group getGroup() {   return group;  }

   public void setGroup(Group group) {   this.group = group;  }

}

public class User {

   private Long groupID;

   @Id  

  @Column(name = "GROUP_ID", length=1)  

  public Long getGroupID() {   return groupID;  }

   public void setGroupID(Long groupID) {   this.groupID = groupID;  }

}

 

一对多[OneToMany]和多对一[ManyToOne] 

public class Enterprise {

   private Long enterpriseID;

   @Id  

  @Column(name = "ENTERPRISE_ID", length = 8)  

  public Long getEnterpriseID() {   return enterpriseID;  }

   public void setEnterpriseID(Long enterpriseID) {   this.enterpriseID = enterpriseID;  }

   private Set<User> users = new HashSet<User>();

   @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER, targetEntity = User.class, mappedBy = "enterprise")

   public Set<User> getUsers() {   return users;  }

   public void setUsers(Set<User> users) {   this.users = users;  }

}

public class User {

   private Enterprise enterprise;

   @ManyToOne(cascade = { CascadeType.MERGE, CascadeType.PERSIST,    CascadeType.REFRESH })  

  @JoinColumn(name = "ENTERPRISE_ID")  

  public Enterprise getEnterprise() {   return enterprise;  }

   public void setEnterprise(Enterprise enterprise) {   this.enterprise = enterprise;  }

}

 

注意fetch = FetchType.EAGER,如果选择LAZY,hibernate在事物结束后会关闭session(好像是session的问题),那么无法在事物之外取到被join出来的记录,会提示session被关闭。

 

 

 

  

注解(annotaion)一对一、一对多、多对一

标签:

原文地址:http://www.cnblogs.com/ning2015/p/4739016.html

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