Stephan
Stephan

Reputation: 43053

How to force foreign key generation between an @Entity and a @ElementCollection?

Here is my code:

@Entity
@Table(name="POSTS")
public class Post {
    @Id
    private Integer id;

    @Column(unique=true, nullable=false)
    private String slug;

    @ElementCollection(fetch = FetchType.LAZY)
    @CollectionTable(
      name = "POSTS_TAGS", 
      joinColumns = { 
          @JoinColumn(name = "POST_SLUG", referencedColumnName = "SLUG")
      }
    )
    private List<String> tags = new ArrayList<>();

}

Hibernate generate two tables: POSTS and POSTS_TAGS.
However it doesn't generate a foreign key in POSTS_TAGS.

If I remove the joinColumns property from @CollectionTable annotation, it generates a foreign key with the id primary key.

How can I instruct Hibernate to generate a foreign key with the joinColumns property?

Hibernate 4.3.7

Upvotes: 0

Views: 320

Answers (1)

V G
V G

Reputation: 19002

Unfortunatelly you cannot instruct Hibernate to generate a foregin key, as it tries automatically to generate them. Because they are generated in other contexts (like for @ManyToOne annotations or when you leave out the @CollectionTable annotation), I am pretty sure it is a bug.

Upvotes: 1

Related Questions