JPA ElementCollection foreign key mapping error

60 views Asked by At

My simple Entity class looks like this -

Entity
@Table(name ="my_class", uniqueConstraints = {@UniqueConstraint(name = "AAndBAndCAndD", columnNames = { "A","B","C","D"}) })
public class MyClass implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

    @Column(name = "A")
    private String A;

    @Column(name = "B")
    private String B;

    @Column(name = "C")
    private Integer C;

    @Column(name = "D")
    private Integer D;

    @Column(name = "E")
    private Long E;

    @ElementCollection(targetClass = String.class, fetch = FetchType.EAGER)
    @CollectionTable(name="values_table", joinColumns = @JoinColumn(name="some_table_id", referencedColumnName = "id"))
    @Column(name="values")
    private Set<String> values;

And I created 2 tables like below - 

CREATE TABLE some_table (
    id serial PRIMARY KEY,
    A character varying(10) NOT NULL,
    B character varying(10) NOT NULL,
    C int NOT NULL,
    D int NOT NULL,
    E bigint,
    UNIQUE (A,B,C,D)
);

CREATE TABLE values_table  (
    some_table_id int NOT NULL,
    values VARCHAR(500),
    constraint fk_values_table_some_table
    foreign key (some_table_id) 
    REFERENCES some_table(id)
);

When I run it as part of a service, I see the following error

Caused by: org.hibernate.MappingException: collection foreign key mapping has wrong number of columns: MyClass.values type: component[id,id] at org.hibernate.mapping.Collection.validate(Collection.java:309) at org.hibernate.mapping.Set.validate(Set.java:40) at org.hibernate.cfg.Configuration.validate(Configuration.java:1364) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1851) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:852) 26 more

I tried different things but can't fix the error. Can anyone help me find out what's wrong with the above code? The names of the classes

I tried to add an Id field to the values table but no luck. I don't understand what's wrong with the foreign key mapping.

1

There are 1 answers

0
S.N On

I think you must define PRIMARY KEY to values_table

Here is code snippet shown below

CREATE TABLE values_table  (
    id serial PRIMARY KEY, -- Add a primary key
    some_table_id int NOT NULL,
    values VARCHAR(500),
    CONSTRAINT fk_values_table_some_table
        FOREIGN KEY (some_table_id) 
        REFERENCES some_table(id)
);