我正在使用Java8和JPA2 / Hibernate5,Spring4和mySQL。
如果有人可以提供帮助,我将不胜感激。
我有以下表格。
+--------+ +------------+ +---------+
| job | | person_job | | person |
+--------+ +------------+ +---------+
| ID | | JOB_ID | | ID |
| | | PER_ID | | |
+--------+ +------------+ +---------+
person
可以包含多个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;
当我直接对数据库运行时,以下SQL工作正常:
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
...
当我运行本机查询(使用上面的sql)时,我收到以下错误:
java.sql.SQLException:找不到列'JOB_ID'。
在 Job.java 中,如果我在JOB_ID
中交换PER_ID
和@JoinTable
,那么我得到:
java.sql.SQLException:找不到列'PER_ID'。
因为上面的SQL对数据库运行正常,我认为问题在于 Job.java 中的连接配置。
更新
我也有以下正常工作:
+--------+ +--------------+ +----------+
| job | | job_location | | location |
+--------+ +--------------+ +----------+
| ID | | JOB_ID | | ID |
| | | LOC_ID | | |
+--------+ +--------------+ +----------+
job
可以包含多个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;
更新
执行本机查询时,我只收到此错误。当我做下面的例子时,它完美地运作。
return (T) entityManager.find(entityClass, id);
我的原生查询有问题吗? (如果person
上没有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();
添加2个注释掉的行没有区别。
答案 0 :(得分:1)
SOLUTION:
I needed to change:
sb.append(" select e.* ");
to
sb.append(" select * ");
答案 1 :(得分:0)
试试这个
// in Job entity
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "person_job", joinColumns = { @JoinColumn(name = "JOB_ID") },
inverseJoinColumns = { @JoinColumn(name = "PER_ID") }
)
private Person person;
...
// in Person entity
@OneToMany(mappedBy = "person")
private List<Job> jobs;