Question

I got a beer

@Entity
@Table(name="beer")
public class Beer implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private Long id;
    private String brewery;
    private String name;

    ...

}

and a bottle

@Entity
@Table(name="bottle")
public class Bottle {

    @Id
    @GeneratedValue
    private Long id;
    private BottleSize size;

    @ManyToOne
    private Beer beer;

    ...
}

and a dao

public class BottleDao {

    private EntityManager entityManager;

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public void saveBottle(Bottle bottle) {
        entityManager.persist(bottle);
    }

    public List<Bottle> findByBeer(Beer beer) {
        Bottle foundBottle = entityManager.find(Bottle.class, beer);
        return null;
    }

    public Bottle findById(Long id) {
        Bottle foundBottle = entityManager.find(Bottle.class, id);
        return foundBottle;
    }

}

If i run

@Test
public void testFindByBeer() throws Exception {
    Beer pils = createHoepfnerPilsner();
    beerDao.saveBeer(pils);
    Beer hefe = createHoepfnerHefe();
    beerDao.saveBeer(hefe);

    Bottle bottlePils = createBottle().withBeer(pils).create();
    bottleDao.saveBottle(bottlePils);
    bottleDao.saveBottle(createBottle().withBeer(hefe).create());

    flushAndClear();
    List<Bottle> bottles = bottleDao.findByBeer(pils);
    assertThat(bottles.size(), is(1));
    assertThat(bottles.get(0).getId(), is(bottlePils.getId()));
}

i get the error java.lang.IllegalArgumentException: Provided id of the wrong type for class Bottle. Expected: class java.lang.Long, got class Beer

What am i missing?

Was it helpful?

Solution

What you're missing is that EntityManager.find() returns the entity identified by the given ID (primary key). And a bottle is not identified by a beer. It's identified by an ID of type Long.

What you need is a JPQL query:

String jpql = "select bottle from Bottle bottle where bottle.beer = :beer";
List<Bottle> bottles = em.createQuery(jpql, Bottle.class)
                         .setParameter("beer", pils)
                         .getResultList();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top