1

I try to create a service with multiple DAO's currently AddressDao and CustomerDao, know I want to create a Transaction that spans the two, something like:

@Inject
private CustomerDao customerDao;

@Inject
private AddressDao addressDao;

Customer getCustomer(int id) {
    Customer customer = customerDao.getCustomer(id);
    customer.setAddress(addressDao.getAddress(customer.getAddressId());
    return customer;
}

Inside the Daos my stuff lookin like that

public class CustomerDaoJdbcImpl implements CustomerDao {
    private static final Logger logger = LoggerFactory.getLogger(CustomerDaoJdbcImpl.class);

    @Inject
    private Database db;


    public Customer getCustomer(int id) {
      try(Connection connection = db.getConnection()) {
      } catch(SQLException e) {
       ...
      }
    }
}

Now since my Connection gets injected into the dao's i can't span a transaction. Also I think i don't get it right and maybe need a good book to understand everything.

What are the preferred solutions? or am I doing it wrong?

Currently I think that I have a solution made up, but it lacks threading.

I got some code from: https://stackoverflow.com/a/2353795/2250209

and here: https://github.com/mybatis/guice/tree/master/src/main/java/org/mybatis/guice/transactional

Currently I have a Database class which pulls the Connection from the Datasource, this class gets injected into a DAO, and if I annotated the DAO or Service the connection will be kept open until I call commit or rollback, but I don't know if that is the best pattern since some people recommend to close the connection inside the method.

Community
  • 1
  • 1
Christian Schmitt
  • 837
  • 16
  • 47

0 Answers0