Note that there are some explanatory texts on larger screens.

plurals
  1. POGuice, JDBC and managing database connections
    text
    copied!<p>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.</p> <p>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:</p> <ul> <li>Where do I create my Datasource?</li> <li>How do I give the repositories access to the connection? (ThreadLocal?)</li> <li>Best way to manage the transaction (Creating an Interceptor for an annotation?)</li> </ul> <p>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.</p> <p>I haven't been able to find many tutorials which cover this, beyond ones which show creating interceptors for transactions.</p> <p>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)</p> <pre><code>@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"; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload