Guice, JDBC and managing database connections
- by pledge
I'm looking to create a sample project while learning Guice which uses JDBC to read/write to a SQL database. However, after years of using Spring and letting it abstract away connection handling and transactions I'm struggling to work it our conceptually.
I'd like to have a service which starts and stops a transaction and calls numerous repositories which reuse the same connection and participate in the same transaction. My questions are:
Where do I create my Datasource?
How do I give the repositories access to the connection? (ThreadLocal?)
Best way to manage the transaction (Creating an Interceptor for an annotation?)
The code below shows how I would do this in Spring. The JdbcOperations injected into each repository would have access to the connection associated with the active transaction.
I haven't been able to find many tutorials which cover this, beyond ones which show creating interceptors for transactions.
I am happy with continuing to use Spring as it is working very well in my projects, but I'd like to know how to do this in pure Guice and JBBC (No JPA/Hibernate/Warp/Reusing Spring)
@Service
public class MyService implements MyInterface {
@Autowired
private RepositoryA repositoryA;
@Autowired
private RepositoryB repositoryB;
@Autowired
private RepositoryC repositoryC;
@Override
@Transactional
public void doSomeWork() {
this.repositoryA.someInsert();
this.repositoryB.someUpdate();
this.repositoryC.someSelect();
}
}
@Repository
public class MyRepositoryA implements RepositoryA {
@Autowired
private JdbcOperations jdbcOperations;
@Override
public void someInsert() {
//use jdbcOperations to perform an insert
}
}
@Repository
public class MyRepositoryB implements RepositoryB {
@Autowired
private JdbcOperations jdbcOperations;
@Override
public void someUpdate() {
//use jdbcOperations to perform an update
}
}
@Repository
public class MyRepositoryC implements RepositoryC {
@Autowired
private JdbcOperations jdbcOperations;
@Override
public String someSelect() {
//use jdbcOperations to perform a select and use a RowMapper to produce results
return "select result";
}
}