java - Spring/JPA 持久性是否可能有 "connection preparation"

标签 java spring jpa spring-data

我有一个 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 的引用,您可能必须创建一个自定义存储库,所有存储库都从中继承:

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

关于java - Spring/JPA 持久性是否可能有 "connection preparation",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30864579/

相关文章:

java - Android 应用程序在 Lollipop 之前的 Java 库上崩溃

java - Spring 新手 - 使用 sec 标签不起作用

Spring Boot 错误相关

java - 设置 remove() 函数不起作用

java - 从异步 rest 模板 spring 返回值

java - PrintStreams 的计时问题

java - 适用于 Http2 的 Instrument Jetty HttpClient

模型中带有列表的 Spring 3 @ModelAttribute

java - EclipseLink ValidationException - 非实体 [class long] 作为关系属性 [fieldproviderId] 中的目标实体

java - Hibernate:避免集合的隐式初始化