How to get connection inside spring transaction?

Imagine this code:

foo() {
     Connection conn = ...;
}

foo()called from a method that has an annotation @Transactional. How to get current JDBC connection? Please note: it foo()is located in a bean (therefore, it can have fields @Autowired), but foo()cannot have parameters (therefore, I cannot pass the connection from somewhere).

[EDIT] I am using jOOQ, which needs either a data source or a connection. My problem: I do not know which transaction manager is configured. It could be anything; A Java EE based on a DataSource is something that gets a data source through JNDI. My code is not an application, it is a library. I need to learn what others have put on my plate. At the same time, I cannot request a Hibernate factory session, because an application using me may not use Hibernate.

But I know that other code, like Spring Hibernate integration, can somehow get the current connection from the transaction manager. I mean, Hibernate does not support Spring Transaction Manager, so the glue should adapt the Spring API to what Hibernate expects. I need to do the same, but I could not understand how it works.

[EDIT2] I know that there is an active transaction (that is, Spring has a Connection instance somewhere or at least a transaction manager that can create it), but my method is not @Transactional, I need to call the constructor, which takes java.sql.Connectionas a parameter. What should I do?

+5
source share
5 answers

( , , Hibernate, , )

. , (, Hibernate), , (, JTA).

@Transactional, , Spring - bean, , bean. proxy, () , . bean. bean , - , " " " ". ; , .

DataSource, DataSource. . , (, Hibernate SessionFactory). , , , .

+7

, DataSourceUtils.getConnection(dataSource), API .

Update: org.springframework.transaction.support.TransactionSynchronizationManager:

, , , , , :

TransactionSynchronizationManager.getResourceMap() ConnectionHolder , , 1 , , , , map.values().get(0), ConnectionHolder, , .getConnection()

, :

TransactionSynchronizationManager.getResourceMap().values().get(0).getConnection()

, : -)

+5

, Plain Jdbc, :

BaseDao {
    @Autowired
    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public Connection getConnection() {
        // ....use dataSource to create connection
        return DataSourceUtils.getConnection(dataSource);
    }
}

FooDao extends BaseDao {
    // your foo() method
    void foo() {
       Connection conn = getConnection();
       //....
    }
}
+4

, , Spring , .

:

, ( ), .

, Spring , , , Spring. Spring " ", . , .

DataSourceUtils .

+3

Spring JDBC, JdbcTemplate JdbcTemplate.execute(ConnectionCallback). , Spring.

+2

All Articles