Pregunta

I have a JPA2 (Hibernate) application which uses a MySQL database with only two tables. One table is called "companies" and the other table is called "employees". Between the two tables there is a one-to-many ralationship (1 company has many employees). The foreign-key column in table "employees" is called "company_id".

In my JPA2 Application I use the following annotations:

In the entity class "Company" I have the following annotation

@OneToMany(cascade = CascadeType.ALL)
private Collection<Employee> employees;

and in class Employee

@ManyToOne
private Company company;

How does JPA know what column it should use to determine all employees of a company. The annotations do not hold this information, but the application works.

Thank you

¿Fue útil?

Solución

The ManyToOne side is missing the optional JoinColumn annotation, which in turn has the optional name attribute defaulting to:

The concatenation of the following: the name of the referencing relationship property or field of the referencing entity or embeddable class; "(underscore)"; the name of the referenced primary key column. If there is no such referencing relationship property or field in the entity, or if the join is for an element collection, the join column name is formed as the concatenation of the following: the name of the entity; "(underscore)"; the name of the referenced primary key column.

On the other side of the relationship, the OneToMany side, it's missing the mappedBy attribute (it should be equal to the name of the field that owns the relationship, in your case "company"). Javadoc says that this attribute is required unless the relationship is unidirectional, so there are chances that the JPA implementation you are using is assuming the relationship is unidirectional.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top