首页 > 解决方案 > entityManager.persist() 在 servlet 中工作,但不在单独的类中

问题描述

我是 JPA 和 Hibernate 的新手。Thing我正在尝试Thing使用entityManager.persist(). 当我在 servlet 中这样做时,Thing会添加 ,但是当我从单独的类中这样做并从 servlet 调用方法时,Thing不会添加 。

这有效:

// servlet

@PersistenceContext
EntityManager em;
@Resource
UserTransaction utx;

protected void processRequest(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    try {

        Thing thing = new Thing("word");

        utx.begin();
        em.persist(thing);
        utx.commit();

    } catch (Exception ex) { }

}

但这不会:

// servlet

protected void processRequest(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    Thing thing = new Thing("word");

    ThingDao thingDao = new ThingDao();
    thingDao.add(thing);

}

鉴于,

// ThingDao

public class ThingDao {

    @PersistenceContext
    EntityManager em;
    @Resource
    UserTransaction utx;

    public void add(Thing thing) {

        try {

            utx.begin();
            em.persist(thing);
            utx.commit();

        } catch (Exception ex) { }

    }

}

为什么第二种方法不起作用?我如何使它工作?

标签: javahibernatejpa

解决方案


通过研究代码,我认为您正在使用 Spring,如果您缺少以下内容:

  1. 类事物道

    @Transactional @Repository 公共类 ThingDao {

  2. serverlet :你需要在那里自动装配 ThingDao

    @Autowired ThingDao td;

希望能帮助到你


推荐阅读