hibenrate(八)一对一对象关系

一、一对一单/双向外键关联(Annotation)
Annotation: @OneToOne @JoinColumn(name="")
XML:<many-to-one unique(单向)
           <many-to-one unique   <one-to-one property-ref(双向)
a)Husband.java
@Entity
public class Husband {
	private int id;
	private Wife wief
	.........
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	@OneToOne								
	@JoinColumn(name="wifeId")
	public Wife getWife() {
		return wife;
	}
	..........
}

b)Wife.java
@Entity
public class Wife {
	private int id;
	……………	   	
         @Id
	@GeneratedValue						public int getId() {						return id;									
	}								
        //双向关联时加入:
         //  private Husband husband;
        // @OneToOne(mappedBy="wife")
         // public Husband getHusband(){
              return husband;;
          
	}
	………………….
}




注:凡是双向关联,必设:mappedBy



二、一对一单/双向主键关联(Annotation) (不重要)有bug
Annotation: @OneToOne @PrimaryKeyJoinColumn

a)Husband.java   Wife.java的设置一样
..............
@OneToOne
@PrimaryKeyJoinColumn
	public Wife getWife() {
		return wife;
	}
...........

你可能感兴趣的:(java,xml)