【问题标题】:Load Collection with entityManager使用 entityManager 加载集合
【发布时间】:2014-04-26 16:15:01
【问题描述】:

我有啤酒

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

    ...
}

还有道

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,得到类 Beer

我错过了什么?

【问题讨论】:

    标签: java hibernate annotations dao entitymanager


    【解决方案1】:

    您缺少的是 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();
    

    【讨论】:

    • 你说得对,我需要搜索啤酒的id:Bottle foundBottle = entityManager.find(Bottle.class, beer.getId());
    • 您评论中的代码没有任何意义。它会查找由啤酒 ID 标识的瓶子。
    • 嗯,它必须可以仅使用注释来完成。我在互联网的某个地方读到,有可能 em.find() 返回一个集合。你能帮我解决这个问题吗?
    • 你为什么不阅读EntityManager的javadoc?它的 find() 方法不返回集合不是很清楚吗?您可以在 Beer 和 Bottle 之间建立双向关联,从而通过其 ID 检索啤酒,然后调用beer.getBottles()。 Hibernate 有一个参考文档。阅读它。
    猜你喜欢
    • 1970-01-01
    • 2013-02-11
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    相关资源
    最近更新 更多