使用entityManager加载集合

时间:2014-04-26 16:15:02

标签: java hibernate annotations dao entitymanager

我喝了一杯啤酒

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

    ...

}

和一瓶

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

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

    @ManyToOne
    private Beer beer;

    ...
}

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

}

如果我跑

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

我收到错误java.lang.IllegalArgumentException:为类Bottle提供了错误类型的id。预期:类java.lang.Long,得到类啤酒

我缺少什么?

1 个答案:

答案 0 :(得分:2)

您缺少的是EntityManager.find()返回由给定ID(主键)标识的实体。并且啤酒没有识别瓶子。它由类型为Long的ID标识。

您需要的是JPQL查询:

String jpql = "select bottle from Bottle bottle where bottle.beer = :beer";
List<Bottle> bottles = em.createQuery(jpql, Bottle.class)
                         .setParameter("beer", pils)
                         .getResultList();