是否可以与Spring / JPA持久性进行“连接准备”

时间:2015-06-16 10:09:47

标签: java spring jpa spring-data

我有一个Spring CrudRepository,它只是一个接口,我有一个持久化上下文类,我已经定义了我的数据源:

@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存储库创建访问代码之前,是否可以“准备连接”?

1 个答案:

答案 0 :(得分:1)

使用AOP似乎是一种方法:使用AOP来丰富Spring Data存储库的示例可以在下面找到:

https://github.com/spring-projects/spring-data-jpa-examples

如果您可以在建议中获得对注入的EntityManager的引用,那么您应该能够使用此处详述的方法之一获取基础连接:

How can i get the session object if i have the entitymanager

要获取对EntityManager的引用,您可能必须创建一个自定义存储库,所有存储库都从该存储库继承:

http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-behaviour-for-all-repositories