Answer the question
In order to leave comments, you need to log in
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;
}
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])
@OneToMany(mappedBy = "id_empl", fetch = FetchType.EAGER)
private List<UserAttr> userAttrList;
Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: ru.....model.UserAttr.id_empl in ru.....dbmaster2.model.User.userAttrList
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question