JPA How to get the value from database after persist

假如想象 提交于 2019-12-11 03:29:27

问题


How to get the value which being saved to database after

entityManager.persist

I am able to get the primary key value from database after calling persist not any other values. E.g.

public void create(Project project) {
    entityManager.persist(project);     
    System.out.println("Id    -- " + project.getProjectId());
    System.out.println("no -- " + project.getProjectNo());
}

From the above code I am able to get the newly inserted value from project.getProjectId, however not able to get project.getProjectNo

The reason why I am able to get projectId is because it is primary key?

How can I get the value of getProjectNo after persist?


回答1:


Try refreshing the entity with the database to get the inserted trigger value.

public void create(Project project) {
        entityManager.persist(project);
        entityManager.getTransaction().commit();
        project = entityManager.find(Project.class, project.getProjectId());
        entityManager.refresh(project);
        System.out.println("Id    -- " + project.getProjectId());
            System.out.println("no -- " + project.getProjectNo());
    }

Documentation



来源:https://stackoverflow.com/questions/17856917/jpa-how-to-get-the-value-from-database-after-persist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!