5

I've got two entities that I want to join together using a field they have in common, called shared_id. The field is not the primary key of either entity. The shared_id is unique - each Hipster will have a unique shared_id.

The tables look like:

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

There is a OneToMany relationship between Hipsters and their Fixies. I've 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 it's upset because the sharedId field is used in a relation, rather than just being a basic field. I haven't included the sharedId field in the Fixie entity, but I get the same result if I do. How do I persuade it to run this query for me? Do I need to change the query or the entities?

Conan
  • 2,288
  • 1
  • 28
  • 42
  • Just thought of another way of expressing this. I've got a bidirectional relationship, but I want to get (and use in queries) the value of the column used to define that relation. – Conan Apr 18 '13 at 16:37
  • 1
    i think it's the same with this. http://stackoverflow.com/questions/13885916/one-to-many-association-join-tables-with-non-primary-key-column-in-jpa – blitzen12 May 03 '13 at 10:28
  • Yep, same deal. Shame it's not possible. I'll definitely bear this situation in mind when designing schemas in future, but in this instance I didn't have a choice. – Conan Jun 21 '13 at 12:23

0 Answers0