@OneToOne annotation

@Target({METHOD, FIELD}) @Retention(RUNTIME)

public @interface OneToOne {

Class targetEntity() default void.class;

CascadeType[] cascade() default {};

FetchType fetch() default EAGER;

boolean optional() default true;

String mappedBy() default “”;

}

1. Unidirectional One-To-One relationship

@JoinColumn

@Entity

@Table(name=”USERS”)

public class User {

@Id

@Column(name=”USER_ID”)

protected String userId;

protected String email;

@OneToOne

@JoinColumn(name=”USER_BILLING_ID”,

referencedColumnName=”BILLING_ID”, updatable=false)

protected BillingInfo billingInfo;

//cascade to save entity

@OneToOne(cascade=CascadeType.PERSIST)

public void setBillingInfo(BillingInfo billing) {…}

}

@Entity

@Table(name=”BILLING_INFO”)

public class BillingInfo {

@Id

@Column(name=”BILLING_ID”)

protected Long billingId;

protected String creditCardType;

protected String creditCardNumber;

protected String nameOnCreditCard;

protected Date creditCardExpiration;

protected String bankAccountNumber;

protected String bankName;

protected String routingNumber;

}

###

@PrimaryKeyJoinColumn
@Entity

@Table(name=”USERS”)

public class User {

@Id

@Column(name=”USER_ID”)

protected Long userId;

@OneToOne

@PrimaryKeyJoinColumn(name=”USER_ID”,

referencedColumnName=”BILLING_USER_ID”)

protected BillingInfo billingInfo;

}

@Entity

@Table(name=”BILLING_INFO”)

public class BillingInfo {

@Id

@Column(name=”BILLING_USER_ID”)

protected Long userId;

}

2. Bidirectional One-To-One relationship

@Entity

public class User {

@Id

protected String userId;

protected String email;

@OneToOne

protected BillingInfo billingInfo;

}

@Entity

public class BillingInfo {

@Id

protected Long billingId;

protected String creditCardType;

protected String routingNumber;

@OneToOne(mappedBy=”billingInfo”, optional=”false”);

protected User user;

}

mappedBy:

The mappedBy=”billingInfo” specification tells the container that the owning side of the relationship exists in the User class’s billingInfo instance variable.

optional:

The @OneToOne annotation on the user field is that the optional parameter is set to false this time. This means that a Billing-Info object cannot exist without a related User object.

About these ads