简体   繁体   English

JPA @GeneratedValue始终为null

[英]JPA @GeneratedValue is allways null

I'm using MySQL / JPA, and the auto-generated IDs on persisted entities are not becoming available even after commit. 我正在使用MySQL / JPA,即使提交后,持久化实体上的自动生成的ID也无法使用。 Here's the code where it happens: 这是发生的代码:

synchronized (em.getTransaction()) {
    while (em.getTransaction().isActive()) {
        em.getTransaction().wait();
    }
    em.getTransaction().begin();
    try {
        em.merge(transmissor);
        em.merge(poco);
        em.flush();
        //em.refresh(poco);           
        System.out.println("ID: " + poco.getIdEstacao());
    } catch (Exception ex) {
        System.out.println(ex.toString());
        ex.printStackTrace();
    }
    // Some other unrelated code...
    em.getTransaction.commit();
    em.getTransaction.notify();
    System.out.println("ID: " + poco.getIdEstacao());
}

Both after em.flush() and after em.getTransaction.commit() , poco.getIdEstacao returns null . em.flush()之后和em.getTransaction.commit()poco.getIdEstacao返回null And if I try to em.refresh(poco) it throws an exception: 如果我尝试em.refresh(poco)它将引发异常:

java.lang.IllegalArgumentException: Can not refresh not managed object:unesp.lebac.aquitel.dataLink.enitity.Poco[ idEstacao=null ].

Any ideas why this happens? 任何想法为什么会发生这种情况? Thanks in advance! 提前致谢!

EntityManager.merge() doesn't modify the object passed as argument, and doesn't make it managed. EntityManager.merge()不会修改作为参数传递的对象,也不会对其进行管理。 It copies the state of the object passed as argument to a managed entity instance, and returns this managed entity instance. 它将作为参数传递的对象的状态复制到托管实体实例,并返回此托管实体实例。 So if you want to get the managed entity, you need 因此,如果要获取托管实体,则需要

poco = em.merge(poco);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM