是否可以进行“连接准备"?具有Spring/JPA持久性 [英] Is it possible to have "connection preparation" with Spring / JPA persistency

查看:54
本文介绍了是否可以进行“连接准备"?具有Spring/JPA持久性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Spring CrudRepository,它只是一个接口,并且我有一个持久化上下文类,在其中定义了我的数据源:

I have a Spring CrudRepository that is just an interface, and I have a persistence context class where I have defined my data source:

@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并在那里返回已准备的连接".

Everything works fine but the database model is such that I actually need to call a stored procedure on the same connection before calling findById from the using code. This procedure must take a parameter that a calling code will know but it will differ between calls so it is not possible just to override DataSource.getConnection and return the "prepared connection" there.

在对Spring存储库进行访问代码之前,有什么方法可以准备连接"?

Is it any way to "prepare a connection" before making an access code to the Spring repository?

推荐答案

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

Using AOP would seem to be one approach: an example of using AOP to enrich Spring Data repositories can be found at the below:

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

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

If you can get a reference to the injected EntityManager within the advice then you should be able to get the underlying connection from that using one of the methods detailed here:

如何获取会话对象(如果我有entitymanager)

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

To get a reference to the EntityManager you may have to create a custom repository from which all your repositories inherit:

查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆