Software Engineering

Unidirectional 1:1 relationships with Hibernate annotations

This is mainly a note to self because I screw up every time I need to write something like that, so here’s an example for myself in the future.

@Entity
@Table( name = "master" )
public class Master {
	@Id
	@GeneratedValue( generator = DBConstants.MASTER_SEQ )
	@SequenceGenerator( name = DBConstants.MASTER_SEQ, sequenceName = DBConstants.MASTER_SEQ )
	private long id;
	@OneToOne( fetch = FetchType.LAZY, optional = false, targetEntity = Detail.class, cascade = CascadeType.ALL )
	@PrimaryKeyJoinColumn
	private Detail detail;
	// ...
}
@Entity
@Table( name = "master_detail" )
public class Detail {
	@Id
	@GeneratedValue( generator = DBConstants.DETAIL_SEQ )
	@SequenceGenerator( name = DBConstants.DETAIL_SEQ, sequenceName = DBConstants.DETAIL_SEQ )
	private long id;
	// ...
}

Reference: java.sun.com, Tadtech

1 Comment

Comments are closed.