如何通过AOP在运行时为每个Session配置Hibernate Statement Inspector
问题:如何在运行时为线程本地Session动态添加StatementInspector
背景
StatementInspector有两种使用场景:
- 会话工厂共享:由会话工厂创建的所有Session共用该实例,必须保证线程安全
- Session专用:为特定Session注册专属实例
我关注的是第二种场景,目前已通过以下代码实现需求,但不想在每个仓库方法或调用中重复修改Session对象,希望仅为特定API调用或仓库方法启用StatementInspector。尝试用切面实现但未成功,想请教有没有更好的方法在运行时为线程本地Session添加StatementInspector。
已实现的可行代码(MyRepository.java)
Session originalSession = em.unwrap(Session.class); SQLStatementInspector sqlStatementInspector = new SQLStatementInspector(); SessionBuilder sessionBuilder = originalSession.sessionWithOptions().statementInspector(sqlStatementInspector); Session newSessionWithStatementInspector = sessionBuilder.openSession(); CriteriaBuilder builder = newSessionWithStatementInspector.getCriteriaBuilder(); ... newSessionWithStatementInspector.createQuery(builder.createQuery()).getResultList();
尝试的切面代码(未成功)
@Aspect @Component public class StatementInspectorAspect { @Autowired private EntityManager em; @Before("execution(* com.ea.MyRepository.findAll(..)) && args(appointmentId, type, sortKey, sortDirection)") public void before(JoinPoint joinPoint, Long appointmentId, String type, String sortKey, String sortDirection) { Session unwrap = em.unwrap(Session.class); SQLStatementInspector sqlStatementInspector = new SQLStatementInspector(); SessionBuilder sessionBuilder = unwrap.sessionWithOptions().statementInspector(sqlStatementInspector); final Session session2 = sessionBuilder.openSession(); this.em = session2; } }
内容的提问来源于stack exchange,提问作者TerNovi
相关产品推荐
相关产品推荐

