【问题标题】:How to get entity id after JPAContainer committed?JPAContainer提交后如何获取实体ID?
【发布时间】:2016-02-17 11:55:16
【问题描述】:

我使用 Hibernate 和 JPAContainer。这里是实体和意外行为部分的代码:

// MyEntity
@Entity
class MyEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;

    private String value;

    // getters and setters...
}

// set up JPAContainer
JPAContainer c = JPAContainerFactory.make(MyEntity.class, "lazyhibernate");
c.getEntityProvider().setEntityManager(null);
c.getEntityProvider().setEntityManagerProvider(entityManagerProvider);
c.getEntityProvider().setLazyLoadingDelegate(new HibernateLazyLoadingDelegate());

final BeanItem<MyEntity> item = new BeanItem<MyEntity>(new MyEntity());
fill(item); // fill item fields...
MyEntity e = item.getBean();
c.addEntity(e);
c.commit();

System.out.println(e.getId()); // return null

如何获取新创建实体的id?

【问题讨论】:

  • 你能贴出MyEntity类的代码吗?
  • @kukis 看看。

标签: java jpa vaadin jpacontainer


【解决方案1】:

只要您不对容器进行提交,您就会从 JPAContainer 中获取作为 ItemID 的 UUID。否则(提交后)使用数据库提供的 ID 再次检索您的 EntityID (EntityItem)。

UUID uuid = (UUID) c.addEntity(e); 
EntityItem<MyEntity> itemUncommitted = c.getItem(uuid) // here you use the UUID to retrieve the Entity
c.commit();
EntityItem<MyEntity> itemCommited = c.getItem(e.getId()); // here you use the ID of the DB 

但我建议您忘记 JPAContainer。它很方便,但问题太多。 我建议您通过帮助类、EJB 等创建一个服务层。在那里您可以从您的 UI 代码中隐藏 JPA 功能。

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 2011-12-31
    • 2014-03-28
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多