pushmatrix
pushmatrix

Reputation: 746

Making foreign keys unique in JPA

Is it possible to make a foreign key unique within a table? Suppose I have entities A and B.

A:

@Entity
class A extends Serializable {
@Id
private long id;

@OneToOne
private B b;
}

B:

@Entity
class B extends Serializable {
@Id
private long id;
}

I want to make it so that an A can have a B, except there can be no other A's with the same B. Ex: a1 has b1, and a2 has b2... in this case, a3 cannot have b1 or b2 since the B's must be unique.

Is there a way to accomplish this? I'd like to be able to put the @Column( unique = true ) annotation above the @OneToOne, but this doesn't seem to be possible.

Upvotes: 3

Views: 2299

Answers (2)

Levente Holló
Levente Holló

Reputation: 724

@JoinColumn does not work.

You need to use something like this:

@Table(name="B",  uniqueConstraints={
   @UniqueConstraint(columnNames={"b_id"})
})

where "b_id" is the name of the foreign key constraint.

Upvotes: 5

user210786
user210786

Reputation:

For sure you can add:

@OneToOne
@JoinColumn(name="COLUMN_NAME", unique=true)

Upvotes: 0

Related Questions