entityManager.persist()在servlet中工作,但不在单独的类中工作

时间:2019-04-03 07:57:35

标签: java hibernate jpa

我是JPA和Hibernate的新手。我正在尝试使用ThingThing插入数据库的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) { }

    }

}

为什么第二种方法不起作用?我该如何运作?

2 个答案:

答案 0 :(得分:0)

带有@Component的注释并自动连接,因为没有DI。

// ThingDao

@Compoenent
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) { }

    }

}

//在servlet中

       @Autowired
       ThingDao td;

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

    Thing thing = new Thing("word");


    td.add(thing);

}

答案 1 :(得分:0)

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

  1. ThingDao类

    @Transactional @资料库 公共课ThingDao {

  2. serverlet:您需要在那里自动连接ThingDao

    @自动连线 ThingDao td;

希望有帮助