java 使用 JPA 更新

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2262824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 20:20:52  来源:igfitidea点击:

update using JPA

javaormjpajta

提问by Pradyut Bhattacharya

I m using glassfish v2 and persistence in a web application.

我在 Web 应用程序中使用 glassfish v2 和持久性。

I m calling persistence codes using a normal java class file inside a web Application

我正在使用 Web 应用程序中的普通 java 类文件调用持久性代码

I can select easily using this code: -

我可以使用此代码轻松选择:-

   @PersistenceUnit
public EntityManagerFactory emf;
EntityManager em;


public List fname (String id) {
    String fname = null;
    List persons = null;
    //private PersistenceManagerFactory persistenceManagerFactory;

    try {
        emf = Persistence.createEntityManagerFactory("WebApplicationSecurityPU");

        em = emf.createEntityManager();
        persons = em.createQuery("select r from Roleuser r").getResultList();

        int i=0;
        for (i=0;i<persons.size(); i++)
            System.out.println("Testing n "+ i +" " + persons.get(i));

    } catch(Exception e) {
        System.out.println("" + e);
    }
    finally {
        if(em != null) {
            em.close();
        }
    }
    return persons;
}

I want to update using JTA as the persistence.xml file has transaction-type="JTA"

我想使用 JTA 进行更新,因为 persistence.xml 文件具有 transaction-type="JTA"

When i try using update using this code i get a nullPointerException without any traces in the log

当我尝试使用此代码进行更新时,我得到一个 nullPointerException,日志中没有任何痕迹

     @PersistenceUnit
public EntityManagerFactory emf;
EntityManager em;
Context context;
@Resource
private UserTransaction utx;

public List fname (String id) {

    String fname = null;
    List persons = null;


    try {
        emf = Persistence.createEntityManagerFactory("WebApplicationSecurityPU");

        utx.begin();
        em = emf.createEntityManager();

        int m = em.createQuery("update Roleuser r set r.firstName = 'Jignesh I' where r.userID=9").executeUpdate();

        utx.commit();


    } catch(Exception e) {
        System.out.println("" + e);
    }
    finally {
        if(em != null) {
            em.close();
        }
    }
    return persons;
}

Any help

任何帮助

Thanks

谢谢

Pradyut

普拉迪特

采纳答案by Pradyut Bhattacharya

well the code should be without any nightmares...(atleast for me in glassfish)
with the persistence.xml having

好吧,代码应该没有任何噩梦......(至少对我来说在 glassfish 中)
,persistence.xml 具有

<persistence-unit name="WebApplicationSecurityPU" transaction-type="RESOURCE_LOCAL">

the code

代码

@PersistenceUnit
public EntityManagerFactory emf;
public EntityManager em;




public EntityManager getEm() {
    emf = Persistence.createEntityManagerFactory("WebApplicationSecurityPU");
    em = emf.createEntityManager();
    return em;
}

public List fname (String id) {

    String fname = null;
    List persons = null;


    try {
        System.out.println("test");

        em = this.getEm();


        em.getTransaction().begin();
        int m = em.createQuery("update Roleuser r set r.firstName = 'Jignesh H' where r.userID=9").executeUpdate();

        em.getTransaction().commit();


    } catch(Exception e) {
        System.out.println("" + e);
    }
    finally {
        if(em != null) {
            em.close();
        }
    }
    return persons;
}

Any improvements are welcome...(actually needed...) (How to go about using @PersistenceContext)

欢迎任何改进......(实际上需要......)(如何使用@PersistenceContext)

Thanks

谢谢

Pradyut

普拉迪特

回答by Pascal Thivent

Your "normal" class is very likely not a managed componenti.e. a class whose life cycle is managed by the container (like Servlets, Servlet Filters, JSP tag handlers, JSF Managed Beans, ...) and can't benefit from resource injection1. So neither the UserTransactionnor the EntityManagerFactoryare injected here, hence the NullPointerException.

您的“普通”类很可能不是托管组件,即生命周期由容器管理的类(如 Servlet、Servlet 过滤器、JSP 标记处理程序、JSF 托管 Bean 等)并且无法从资源注入中受益1. 所以这里既UserTransaction没有EntityManagerFactory注入也没有注入,因此NullPointerException.

Honestly, you should try to use a container managed EntityManager, this would make your code less messy. If you cannot get it injected, get it via a JNDI lookup. See the resource below.

老实说,您应该尝试使用容器管理EntityManager,这将使您的代码不那么混乱。如果无法注入,请通过 JNDI 查找获取。请参阅下面的资源。

1Have a look at Web Tier to Go With Java EE 5: A Look at Resource Injectionfor a nice overview of what can be injected, and where.

1查看Web Tier to Go With Java EE 5: A Look at Resource Injection以很好地概述可以注入的内容和位置。

Resources

资源

References

参考

  • JPA 1.0 specification
    • Section 5.2 "Obtaining an Entity Manager"
    • Section 5.6 "Container-managed Persistence Contexts"
  • JPA 1.0 规范
    • 第 5.2 节“获取实体管理器”
    • 第 5.6 节“容器管理的持久化上下文”

回答by Bozho

  1. Perhaps your bean isn't managed - i.e. it's not part of any context (spring, EJB). How are you creating your object?
  2. You really should not call createEntityManager()- inject one using @PersistenceContext
  3. You must be absolutely sure you need JTA before using it.
  4. You seem to be using PersistenceUnit, but then re-assign the etm- I'd suggest drop both and see p2 above.
  1. 也许你的 bean 没有被管理——即它不是任何上下文(spring、EJB)的一部分。你是如何创建你的对象的?
  2. 你真的不应该打电话createEntityManager()- 使用注入一个@PersistenceContext
  3. 在使用它之前,您必须绝对确定您需要 JTA。
  4. 您似乎正在使用PersistenceUnit,但随后重新分配了etm- 我建议同时删除两者并参见上面的 p2。

If you are not using any dependecy injection at all, then drop all the annotations, retain the current code, and type:

如果您根本没有使用任何依赖注入,则删除所有注释,保留当前代码,然后键入:

em.getTransaction().begin();
...
em.getTransaction().commit();

(and define RESOURCE_LOCALin your persistence.xml. You really don't need JTA)

(并RESOURCE_LOCAL在你的persistence.xml中定义。你真的不需要JTA)