我有两个实体,我想使用他们共同的字段连接在一起,称为shared_id。该字段不是任一实体的主键。 shared_id是唯一的 - 每个Hipster都有一个唯一的shared_id。
表格如下:
Hipster Fixie
========= ========
id id
shared_id shared_id
Hipsters和他们的Fixies之间存在OneToMany关系。我尝试过这样的事情:
@Entity
public class Hipster {
@Id
@Column(name = "id")
private Integer id;
@Column(name = "shared_id")
private Integer sharedId;
@OneToMany(mappedBy = "hipster")
private List<Fixie> fixies;
}
@Entity
public class Fixie {
@Id
@Column(name = "id")
private Integer id;
@ManyToOne
@JoinColumn(name = "shared_id", referencedColumnName = "shared_id")
private Hipster hipster;
}
@Repository
public class HipsterDAO {
@PersistenceContext
private EntityManager entityManager;
public Hipster getHipsterBySharedId(Integer sharedId) {
String queryString = "SELECT h FROM Hipster h WHERE h.sharedId = :sharedId";
TypedQuery<Hipster> query = entityManager.createQuery(queryString, Hipster.class);
query.setParameter("sharedId", sharedId);
try {
return query.getSingleResult();
} catch (PersistenceException e) {
return null;
}
}
}
现在,我的DAO给了我这个错误:
java.lang.IllegalArgumentException: Can not set java.lang.Integer field Hipster.sharedId to java.lang.Integer
我认为它很难过,因为sharedId字段用于关系,而不仅仅是一个基本字段。我还没有在Fixie实体中包含sharedId字段,但如果我这样做,我会得到相同的结果。我如何说服它为我运行此查询?我是否需要更改查询或实体?