Monday, April 9, 2012

Getting a Datasource/Connection from a Hibernate Session a.k.a. Get the Database Product Name at runtime from a Spring JpaRepository

I found it necessary to get a connection from a Spring JpaRepository in order to see if we can use a SQL Server specific query for some tests. We need to jump through some hoops in order to get there though.

First step is to get the EntityManager (note this method requires the ReflectiontestUtils).


Next Step is to use the EntityManager's unwrap method along with Spring's SessionFactoryUtils to get the DataSource:


And with a datasource we can grab the connection (in this example I'm looking at the DB name):

2 comments: