如何知道 persist 方法是否有效?我只能想到两种解决方案,但肯定有一些更直接或准备好的解决方案。无论如何,我想知道是否有人知道这个解决方案的问题或更好的替代方案?谢谢?
当我使用persist时我没有返回来检查该方法是否成功完成。 (也许是 boolean 值或实体本身来检查 id)
UserEntity e = new UserEntity();
e.setName("Name");
e.setAge(30);
em.persist(e);
选项#1 EntityManger 包含方法 http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html#contains
UserEntity e = new UserEntity();
e.setName("Name");
e.setAge(30);
em.persist(e);
----
return em.contains(e);
选项#2 返回实体 ID
当我持久化实体时,我可以进行commit
并返回实体或实体id,如果我有id,持久化方法应该成功。
UserEntity e = new UserEntity();
e.setName("Name");
e.setAge(30);
em.persist(e);
em.commit();
----
return e;//or return e.getId();
最佳答案
对于选项 1 : em.contains(e)
仅检查实体是否处于持久化上下文的托管状态,而不检查结果,因此这是仅检查实体是否处于托管状态
对于选项2:它将返回持久化的值,或者如果持久化失败则立即抛出异常。
但是一旦实体处于托管状态并且被持久化,实体将使用数据库中的数据进行更新,因此只需返回实体就足够了。
If you really want to flush the data instead of jpa doing itself call
em.flush()
this will flush the data and the the entity object will hold the persisted value from the database.
em.persist(e);
em.flush(); //not really required
return e; //this will return the object that is already persisted in the database
检查entity life cycle了解更多信息
关于java - EntityManager contains 或 findById after persist 来了解 persist 方法是否有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45465735/