0

I use Hibernate and JPAContainer. Here the code of entity and unexpected behavior part:

// 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

How to get id of newly created entity?

codemonkey
  • 157
  • 2
  • 11

1 Answers1

0

As long as you do not do a commit on the container you get back an UUID as an ItemID from the JPAContainer. Otherwise (after commit) use the ID given by the database to retrieve your EntityID (EntityItem) again.

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 

But I would recommend you to forget about JPAContainer. It is handy but has too many issues. I would suggest you to create a service layer either trough a helper class, EJB etc. There you can hide the JPA-Functions from your UI code.

nik
  • 76
  • 5