JPA Join an arbitrary field (not a primary key)

I have two objects that I want to join with, using the field that they have, called shared_id. A field is not the primary key of any object. Shared_id is unique - each hipster will have a unique shared_id.

The tables look like this:

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

There is a OneToMany relationship between Hipsters and their Fixies. I tried something like this:

 @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; } } } 

Now my DAO gives me this error:

 java.lang.IllegalArgumentException: Can not set java.lang.Integer field Hipster.sharedId to java.lang.Integer 

I think this is frustrating because the sharedId field is used in relation, and not just as the main field. I did not include the sharedId field in the Fixie object, but I get the same result, if so. How can I convince him to fulfill this request for me? Do I need to modify a query or entities?

+4
source share

All Articles