5

我有两个实体,我想使用它们共同的字段(称为 shared_id)将它们连接在一起。该字段不是任一实体的主键。shared_id 是唯一的——每个 Hipster 都有一个唯一的 shared_id。

表格如下所示:

Hipster    Fixie
=========  ========
id         id
shared_id  shared_id

Hipster 和他们的 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 字段,但是如果我这样做了,我会得到相同的结果。如何说服它为我运行此查询?我需要更改查询或实体吗?

4

0 回答 0