我们正在用Spring和hibernate开发一个应用程序。道层类如下所示:
@Autowired
private StoredDao storedDao;
@PersistenceUnit
private EntityManagerFactory emf;
public boolean method() throws Exception {
EntityManager em;
Session session;
Transaction tx;
try{
em = emf.createEntityManager();
session = em.unwrap(Session.class);
tx = session.beginTransaction();
...
...
...
storedDao.processBills(billId, billStatus, billApprover);
...
...
tx.commit();
} catch(Exception e){
tx.rollback();
}
}
@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
@Override
public void processBills(int billId, int billStatus, String billApprover, Session session){
try{
final Work processBillCaller = buildStoredProcCaller(billId, billStatus, billApprover);
session.doWork(processBillCaller);
} catch (Exception e){
throw new Exception("message");
}
}
private Work buildStoredProcCaller(int billId, int billStatus, String billApprover) {
return new Work() {
@Override
public void execute(Connection con) throws SQLException {
try (CallableStatement callableStmt = con.prepareCall(<procName>);) {
callableStmt.setInt(1, billId);
callableStmt.setString(2, billStatus);
callableStmt.setInt(3, billApprover);
callableStmt.executeUpdate();
} catch (Exception e) {
throw new SQLException("message");
}
}
};
}
方法()中的所有查询都会被执行。此外,存储过程在方法processBills中执行。在日志中,消息如下:
ABC1 org.hibernate.SQL {调用procName ?,?,?}
但是存储过程的结果没有提交。
在存储过程调用之前和之后有许多session.save()和session.merge()调用。当执行tx.commit()时,除了存储过程结果之外,所有内容都会被执行。不会有任何错误。
我还试着注释@Transactional,然后运行上面的代码流。但是,存储过程代码仍未实现。
请让我知道我做错了什么。
发布于 2017-04-09 21:24:11
嗨,我找到了答案。在调用存储过程之前,新账单尚未持久化到数据库中。只有在调用transaction.commit()时,它才会持久化。因此,当存储过程运行时,要处理的账单不在数据库中。
因此,在存储过程调用之前,现在我调用session.flush(),然后执行存储过程。它起作用了。
https://stackoverflow.com/questions/43181625
复制