I am using Java8 with JPA2/Hibernate5, Spring4 and mySQL.
If anyone can help, I would appreciate it.
I have the following tables.
+--------+ +------------+ +---------+
| job | | person_job | | person |
+--------+ +------------+ +---------+
| ID | | JOB_ID | | ID |
| | | PER_ID | | |
+--------+ +------------+ +---------+
A person
can have many jobs
.
Job.java
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "person_job", joinColumns = {
@JoinColumn(name = "PER_ID", referencedColumnName = "ID") }, inverseJoinColumns = {
@JoinColumn(name = "JOB_ID", referencedColumnName = "ID", unique = true) })
private Person person;
The following SQL works fine when I run it directly against the database:
select
e.*, p.*
from
www.job as e
inner join
www.person_job as pj
on e.id=pj.JOB_ID
inner join
www.person as p
on pj.PER_ID=p.ID
...
When I run a native query (with the above sql), I get the following error:
java.sql.SQLException: Column 'JOB_ID' not found.
In Job.java, if I swap the JOB_ID
and PER_ID
around in the @JoinTable
, then I get:
java.sql.SQLException: Column 'PER_ID' not found.
Because the above SQL runs fine against the database, I think the problem is with join configuration in Job.java.
UPDATE
I also have the following that works correctly:
+--------+ +--------------+ +----------+
| job | | job_location | | location |
+--------+ +--------------+ +----------+
| ID | | JOB_ID | | ID |
| | | LOC_ID | | |
+--------+ +--------------+ +----------+
A job
can have many locations
.
jobs.java
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "job_location", joinColumns = {
@JoinColumn(name = "JOB_ID", referencedColumnName = "ID") }, inverseJoinColumns = {
@JoinColumn(name = "LOC_ID", referencedColumnName = "ID", unique = true) })
private Set<Location> locations;
UPDATE
I only get this error when I execute a native query. When I do the following fr example, it works perfectly.
return (T) entityManager.find(entityClass, id);
Is there something wrong with my native query? (This query works if I don't have the person
column on Jobs.java
).
StringBuilder sb = new StringBuilder();
sb.append(" select e.* ");
sb.append(" from ");
sb.append(" www.job as e ");
//sb.append(" inner join www.person_job as pj on e.id = pj.JOB_ID ");
//sb.append(" inner join www.person as p on pj.PER_ID = p.id ");
sb.append(" where e.id = :id ");
Query q = entityManager.createNativeQuery(sb.toString(), JobWithDistance.class);
q.setParameter("id", id);
List<Job> jobs = (List<Job>) q.getResultList();
Adding the 2 commented out lines makes no difference.