0

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);
}

Then

  @Autowired
  protected DataRepository repository;

  ...

  Data data = repository.findById(1234);

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.

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

Audrius Meškauskas
  • 20,936
  • 12
  • 75
  • 93
  • Via AOP? See here which includes "Example of how to enrich the repositories with AOP" https://github.com/spring-projects/spring-data-jpa-examples/blob/master/spring-data-jpa-interceptors/src/main/java/org/spring/data/jpa/sample/interceptors/ApplicationConfiguration.java – Alan Hay Jun 16 '15 at 10:27
  • This is interesting, trying now ... – Audrius Meškauskas Jun 16 '15 at 10:37
  • If you can get a handle on the current EntityManager then you should be able to get the underlying connection: http://stackoverflow.com/questions/4148231/how-can-i-get-the-session-object-if-i-have-the-entitymanager – Alan Hay Jun 16 '15 at 10:56
  • Ae, get session through the EntityManager that can be injected, then connection. This is the answer, I would accept. – Audrius Meškauskas Jun 17 '15 at 06:38

1 Answers1

1

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

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:

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

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

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

Community
  • 1
  • 1
Alan Hay
  • 22,665
  • 4
  • 56
  • 110