This is a common problem in DAO pattern. This is why AOP was invented. When you use DAO pattern, all of your DAO classes have boilerplate code. The way this problem is solved is by Weaving the boiler plate code into your code. So, basically, you will put a transaction annotation on your method, and your method won't need the boilerplate code to open and close the transaction. Your code only contains business logic. The framework will inject the boilerplate code into your code
Another solution is using a template helper like this, where the template does all the boilerplate initialization and cleanup, and invokes your DB logic inbetween:
It's not as elegant as AOP, but still reduces the boilerplate. This pattern is followed in Spring framework to help with both hibernate and JDBC operations. In recent versions, spring has deprecated them because they couple your code to spring framework,
but if you're writing your own templates, it's not a problem.