java - 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) { }
}
}
为什么第二种方法不起作用?我如何使它工作?
解决方案
通过研究代码,我认为您正在使用 Spring,如果您缺少以下内容:
类事物道
@Transactional @Repository 公共类 ThingDao {
serverlet :你需要在那里自动装配 ThingDao
@Autowired ThingDao td;
希望能帮助到你
推荐阅读
- python - 将可调用的 MagicMock return_value 实例方法更改为 PropertyMock
- sql-server - 找不到列“a”或用户定义的函数或聚合“a.Quantity”,或者名称不明确
- html - 简单的 QlikView 混搭(iframe 嵌入) - 为什么它适用于匿名?
- javascript - Java Web Audio Api - 如何将base64Sting保存到音频文件
- php - JSON foreach循环将数据两次写入文件
- spring-boot - 来自 Gradle 任务的 HTTP 发布 - Groovy
- excel - 从用户窗体导出图像
- c# - IStreamProvider.ReleaseStream 方法有什么用途?
- vba - 防止VBE在后台不断更换模块
- ruby-on-rails - Rubocop Metrics/CyclomaticComplexity 以防万一