我正在使用Spring data jpa和jdbc(使用entityManager.unwrap(Session.class))连接。
我的请求流经 3 种方法。第一 -> 第二 -> 第三。
第一个和第三个用@Transactional 注释。
在第一种和第二种方法中,通过 JPA CRUD 存储库保存实体。
在第三种方法中,使用基本的 jdbc 查询来检索第二种方法中保存的值。
正如我们所知,@Transaction 实体在 JPA 提交事务之前不会提交到数据库。
我也在第二种方法中使用了 saveAndFlush,但看不到使用 jdbc 查询在方法 3 中检索更新的值。
第一种方法 - update()
@Transactional
@Override
public ApiResponse update(RequestInput input) {
ApiResponse response = doRestOfWork(input); // calling 2nd method
// .... some other entity save....
}
第二种方法 - doRestOfWork() :设置 status=true 并调用 saveAndFlush 方法
@Override
public ApiResponse doRestOfWork(Request request) {
Insight insight = insightRepository.findOne(request.getTypeId());
insight.setStatus(true);
insightRepository.saveAndFlush(insight);
processOperation(); // calling 3rd method
}
第三种方法 - processOperation():通过 jdbc 连接检索更新的状态值。
@Transactional
public void processOperation() {
Connection conn = null;
SessionImplementor sessionImpl = (SessionImplementor) entityManager.unwrap(Session.class);
try {
conn = sessionImpl.getJdbcConnectionAccess().obtainConnection();
Connection conn = null;
String stmt = "SELECT status from insight";
PreparedStatement ps = conn.prepareStatement(stmt);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
boolean value = rs.getBoolean(status); // returning false, i want this to return true as already set true in 2nd method and called saveAndFlush
}
} catch (SQLException ex) {
} finally {
JdbcUtility.closeResources(conn, ps, rs);
}
}
InsightRepository 正在扩展 JpaRepository
@Repository
public interface InsightRepository extends JpaRepository<Insight, Long> {}
I want updated value of status (which is boolean true - updated in method 2) in method 3. How to achieve this ?
更新
我搜索了很多,不认为一个方法如果用 @Transactional 注解的话那么您可以在完成 JPA 事务之前提交更改。所以解决办法就是删除@Transactional如果想控制JPA事务,请使用注释并使用entityManager.getTransaction()。
最佳答案
在与第二个方法不同的bean中使用@Transactional(propagation = Propagation.REQUIRES_NEW)
注释创建一个用于更新的方法(第四个方法),并将第二个方法更改为调用第四个方法,如下所示:
@Component //or Service etc..
public class AnotherBean{
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void doUpdateWork(Request request){
Insight insight = insightRepository.findOne(request.getTypeId());
insight.setStatus(true);
insightRepository.save(insight);
}
}
和
@Override
public ApiResponse doRestOfWork(Request request) {
anotherBean.doUpdateWork(request);
processOperation(); // calling 3rd method
}
关于java - 如何在@Transactional模式下强制提交实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50654222/