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

Hibernate-----一对一共享主键关联映射(注解)

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

标签:hibernate   共享主键   orm   注解   

One(‘多’)

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
 @Entity
public class Wife {
    private int id;
    private String name;
 
    private Husband husband;
 
    /**
     * wife的ID是根据husband的ID来赋值的,需设置ID生成器的策略为foreign
     *
     * 参数中指定wife的ID是使用husband对象中的ID
     */
    @Id
    @GenericGenerator(name = "pkGenerator",
strategy = "foreign",
parameters = { @Parameter(name = "property", value = "husband") })
    @GeneratedValue(generator = "pkGenerator")
    public int getId() {
       return id;
    }
 
    public void setId(int id) {
       this.id = id;
    }
 
    public String getName() {
       return name;
    }
 
    public void setName(String name) {
       this.name = name;
    }
 
    public void setHusband(Husband husband) {
       this.husband = husband;
    }
 
    @OneToOne(cascade = CascadeType.ALL)
    public Husband getHusband() {
       return husband;
    }
}
 

One(‘一’)

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
 
@Entity
public class Husband {
    private int id;
    private String name;
    private Wife wife;
 
    @Id
    @GeneratedValue
    public int getId() {
       return id;
    }
 
    public String getName() {
       return name;
    }
 
    // 该注解只能写在主(生成ID)的一端
    @OneToOne(cascade = CascadeType.ALL)
    @PrimaryKeyJoinColumn
    public Wife getWife() {
       return wife;
    }
 
    public void setId(int id) {
       this.id = id;
    }
 
    public void setName(String name) {
       this.name = name;
    }
 
    public void setWife(Wife wife) {
       this.wife = wife;
    }
}
 






Hibernate-----一对一共享主键关联映射(注解)

标签:hibernate   共享主键   orm   注解   

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

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