我有一个 Spring CrudRepository
它只是一个接口(interface),我有一个持久上下文类,我在其中定义了我的数据源:
@Configuration
@EnableTransactionManagement
public class PersistenceContext {
@Bean(name="dataSource", destroyMethod = "close")
public DataSource dataSource() throws SQLException {
return ...
public interface DataRepository extends CrudRepository<Data, Long> {
Data findById(long id);
}
然后
@Autowired
protected DataRepository repository;
...
Data data = repository.findById(1234);
一切正常,但数据库模型是这样的,我实际上需要在从使用代码调用 findById
之前在同一连接上调用存储过程。此过程必须采用调用代码知道的参数,但它在调用之间会有所不同,因此不可能仅重写 DataSource.getConnection 并在那里返回“准备好的连接”。
在对 Spring 存储库进行访问代码之前,有什么方法可以“准备连接”吗?
最佳答案
使用 AOP 似乎是一种方法:可以在下面找到使用 AOP 丰富 Spring Data 存储库的示例:
https://github.com/spring-projects/spring-data-jpa-examples
如果您可以在建议中获取对注入(inject)的 EntityManager 的引用,那么您应该能够使用此处详细介绍的方法之一从中获取底层连接:
How can i get the session object if i have the entitymanager
要获取对 EntityManager 的引用,您可能必须创建一个自定义存储库,所有存储库都从中继承:
关于java - Spring/JPA 持久性是否可能有 "connection preparation",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30864579/