【问题标题】:Is it possible to have "connection preparation" with Spring / JPA persistency是否可以通过 Spring / JPA 持久性进行“连接准备”
【发布时间】:2015-09-01 02:16:01
【问题描述】:

我有一个 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 存储库进行访问代码之前,有什么方法可以“准备连接”吗?

【问题讨论】:

标签: java spring jpa spring-data


【解决方案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

【讨论】:

    猜你喜欢
    • 2018-02-25
    • 1970-01-01
    • 2020-02-18
    • 2011-07-02
    • 1970-01-01
    • 2015-04-26
    • 2012-12-12
    • 2018-11-27
    • 2017-09-02
    相关资源
    最近更新 更多