Java EntityManager没有';t立即将实体存储到datatabase

Java EntityManager没有';t立即将实体存储到datatabase,java,hibernate,jpa,Java,Hibernate,Jpa,当使用saveOrUpdate方法保存新对象时,它会保存该对象,但下次当我在分离模式下修改该对象并通过saveOrUpdate方法保存该对象时,它将始终处于while循环中,而不会超出循环。请帮助我,我是JPA新手,我正在将我的项目从Hibernate转换为JPA。1)看起来你在JPA方面有问题。尝试检查它(我在代码中添加了带有注释的新行): 或 2) 尝试使用 public static MyMessage saveOrUpdate(MyMessage msg) { ... E

当使用saveOrUpdate方法保存新对象时,它会保存该对象,但下次当我在分离模式下修改该对象并通过saveOrUpdate方法保存该对象时,它将始终处于while循环中,而不会超出循环。请帮助我,我是JPA新手,我正在将我的项目从Hibernate转换为JPA。

1)看起来你在JPA方面有问题。尝试检查它(我在代码中添加了带有注释的新行):

2) 尝试使用

public static MyMessage saveOrUpdate(MyMessage msg) {
    ...
    EntityManager em1 = factory.createEntityManager();
    Cache cache = em1.getEntityManagerFactory().getCache(); // get cache 
    cache.evictAll(); // remove all Entity from Cache
    MyMessage msss= em1.find(MyMessage.class, m.getId());
    System.out.println(msss);// prints null
    return m;
} 

3) 尝试将merged更改为persist,而不是
m=em.merge(msg)使用
em.persist(msg);m=味精

您能否按预期打印在'find(..)`method?m.getId()=2916之前看到的
m.getId()
的值。当我重复寻找元素的过程时,就像。EntityManager em1=factory.createEntityManager();System.out.println(“首次尝试加载id”+m.getId());MyMessage msss=em1.find(MyMessage.class,m.getId());系统输出打印LN(msss);EntityManager em2=factory.createEntityManager();System.out.println(“第二次尝试加载id”+m.getId());MyMessage msss2=em2.find(MyMessage.class,m.getId());系统输出打印LN(msss2);然后第二次它从数据库中获取对象。但是第一次我没有得到我期望的任何对象。我想知道为什么第二次它能够正确地获取对象,而不是第一次它自己。只是想检查你使用的代码是否与你发布的代码相同或有细微的更改?当你发出“查找”命令时,日志中会显示什么?我已经尝试过了,但仍然无法得到预期的结果。它仍然打印空。我已经按照您的建议更新了我的代码,但仍然出现问题。谢谢大家的评论。实际上这就是数据库隔离级别设置的问题。
public static MyMessage saveOrUpdate(MyMessage msg) {
    ...
    EntityManager em1 = factory.createEntityManager();
    Cache cache = em1.getEntityManagerFactory().getCache(); // get cache 
    cache.evictAll(); // remove all Entity from Cache
    MyMessage msss= em1.find(MyMessage.class, m.getId());
    System.out.println(msss);// prints null
    return m;
} 
    em.flush();
    EntityManager em1 = factory.createEntityManager();
    MyMessage msss= em1.find(MyMessage.class, m.getId());
    System.out.println(msss);// prints null
    return m;