Implement foreign keys in JPA

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

A:

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

@OneToOne
private B b;
}

IN:

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

I want to make sure that A can have B, except that there cannot be another A with the same B. Ex: a1 has b1 and a2 has b2 ... in this case a3 cannot have b1 or b2, since B must be unique.

Is there any way to do this? I would like the @Column (unique = true) annotation to be higher than @OneToOne, but that seems impossible.

+3
source share
2 answers

Of course you can add:

@ One to one
@JoinColumn (name = "COLUMN_NAME", unique = true)

0
source

@JoinColumn is not working.

- :

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

"b_id" - .

+5

Source: https://habr.com/ru/post/1722847/


All Articles