P
P
p-oleg2018-10-05 13:17:45
Java
p-oleg, 2018-10-05 13:17:45

How to do @OneToMany on a table that doesn't have a primary key, but has an @EmbeddedId?

There is a table of users employees :
id (primary key) | name | last name
1 | Vasya | Ivanov
2 | Vanya | Petrov
There is a table with attributes for employees employees_attr :
id (from employees) | Attr Name | Attr Value
1 | attr name 1 | attr value 1
1 | attr name 2 | attr value 2
2 | attr name 1 | attr value 1
2 | attr name 2 | attr value 2
This table does not have a primary key (I'm not its author), but there is a unique key id - attr_name
I want to receive in entity for the user the list of its attributes.
I make an entity for employees:

@Table(name = "employees")
public class User {
    @Id
    @Column(name = "id_empl")
    protected Integer id_empl;

    @NotBlank
    @Column(name = "name_employee")
    private String name;
...
   // Так как в employees_attr нет первичного ключа, а JPA требует его, то пришлось сделать @Embeddable
    @OneToMany(mappedBy = "userAttrPK")
    private List<UserAttr> userAttrList;
...}

@Embeddable
public class UserAttrPK implements Serializable {
    @Column(name = "id_empl")
    private int id_empl;

    @NotBlank
    @Column(name = "attr_name")
    private String attrName;
}

@Table(name = "employees_attr")
public class UserAttr {
    @EmbeddedId
    UserAttrPK userAttrPK;

    @NotBlank
    @Column(name = "attr_value")
    private String attrValue;
}

In this scenario, I get an error:
Caused by: org.hibernate.MappingException: Foreign key (FKelqockn69dnn2u8v0kib2m8ik:employees_attr [attr_name,id_empl])) must have same number of columns as the referenced primary key (employees [id_empl])

Here it is clear what he wants, but the structure of the tables is like this.
If the user writes like this:
@OneToMany(mappedBy = "id_empl", fetch = FetchType.EAGER)
    private List<UserAttr> userAttrList;

We'll get an error:
Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: ru.....model.UserAttr.id_empl in ru.....dbmaster2.model.User.userAttrList

That is, on the one hand, I need to make a primary key in the attribute table, because this is required by JPA, and on the other hand, a composite primary key is not suitable for linking to a user table.
How can the situation be resolved?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question