I have such things as:
1) DAO class with methods, used to perform transaction, such as withdrawSum(int idAccount, float amount) and putSum(int idAccount, float amount) which use java.sql.Connection and java.sql.PreparedStatement classes to perform atomic operations with DB.
2) java.lang.reflect.InvocationHandler implementor, whick is used to get connection before transaction and commit/rollback after transaction:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Connection connection = null;
try{
connection = DaoUtil.INSTANCE.getConnection();
connection.setAutoCommit(false);
method.invoke(connection, args);
connection.commit();
} catch(InvocationTargetException ex){
connection.rollback();
} finally{
DaoUtil.INSTANCE.closeConnection(connection);
}
return null;
}
3) Transaction manager, which creates Proxy instance and with its help calls method which executes transaction, something like this:
TransactionManager transManager = new TransactionManager();
InvocationHandler transHandler = new MyInvocationHandler(transManager);
TransactionManager proxy = (TransactionManager) Proxy.newProxyInstance(
transManager.getClass().getClassLoader(), transManager.getClass().getInterfaces(), transHandler);
proxy.transferMoney(withdrawAccountid, putAccountId, transactionSum);
.....
public void transferMoney(int withdrawAccountid, int putAccountId, float transactionSum){
AccountDao.getInstance().withdrawSum(withdrawAccountid, transactionSum);
AccountDao.getInstance().putSum(putAccountId, transactionSum);
}
The question is: to execute statement in DAO methods, I need initialized Connection object. It is intialized and passed to the invoke-method of the InvocationHandler. How it should be correctly initialized in DAO-methods? Any ideas? Thanks in advance.
Since transactions are naturally associated with threads, a typical approach here is to store Connection in a ThreadLocal storage during the scope of transaction.
Then you can make these connections available to DAOs using different approaches:
DAOs can obtain Connections by calling some static method
A custom DataSource can be injected into DAOs - its getConnection() method would return the connection associated with current transaction, note that connection should be proxied in order to ignore close(). This approach doesn't couple your DAOs with transaction management code.
Also note that all these things are already implemented by some libraries, for example, by Spring Framework. Perhaps you can leverage it instead of creating your own solution, or at least take a look at their design (in Spring, different approaches for obtaining connections are implemented by DataSourceUtils and TransactionAwareDataSourceProxy, respectively).
See also:
10. Transaction Management
12. Data access with JDBC
Related
I have got:
a DAO class in JOOQ that in its constructor takes a javax.sql.DataSource, which is injected by Guice
a service class that calls the methods from the DAO class
I want to:
be able to annotate a few methods inside the service class as methods requiring a transaction
Possible solution: https://github.com/jOOQ/jOOQ/tree/master/jOOQ-examples/jOOQ-spring-guice-example i.d.:
a method interceptor invoked when a method is annotated with the Transactional annotation
the method interceptor calls rollback() if there were exceptions or commit() if everything was fine
Guice provides a javax.sql.DataSource (BoneCP pooled connection)
the BoneCP pooled connections have the defaultAutoCommit attribute set to false
Finally, my question:
I want the datasource with autocommit set to false to be injected into all the methods that are called from the method annotated with #Transactional, in all the other cases the datasource with autocommit set to true
How this can be achieved?
There is a simple but not elegant way: create two DataSource instances and inject appropriately.
There is also a bit more complex way with a single DataSource instance. Roughly:
AutoCommit is a property of java.sql.Connection and there is a setter for it.
Implement org.jooq.ConnectionProvider to make JOOQ use your DataSource instance.
This ConnectionProvider implementation will have a special method, e.g. startTransaction() that can create a connection with autocommit=false and cache it in a ThreadLocal member. I.e.
Connection conn = dataSource.createConnection();
conn.setAutoCommit(false);
threadLocal.set(conn);
return conn;
ConnectionProvider.acquire() will do smth like (simplified version):
return threadLocal.get() != null ?
threadLocal.get() :
dataSource.createConnection();
Other two "special" methods would be commit() and rollback() - they will do a corresponding operation on the cached connection, close the connection and remove it from threadLocal.
The #Transactional method interceptor will call the "special" methods
try {
connectionProvider.startTransaction();
interceptedMethod.invoke();
connectionProvider.commit();
} catch (Exception e) {
connectionProvider.rollback();
}
Essentially, this is the most simple transaction manager.
I want to create instances of a class which will have access to the underlying Embedded derby database and pass this class to each bundle binding to my database bundle using declarative services.
I have seen in the derby documentation that sharing one connection for multiple threads has many pitfalls. So I was thinking to create a connection for each instance of the class I am creating. Since I only want a very simple way to just create multiple connections and manage them, using "MiniConnectionPoolManager" here seems like a good option. The sample code for derby is shown below:
org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource dataSource = new org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource();
dataSource.setDatabaseName("c:/temp/testDB");
dataSource.setCreateDatabase("create");
MiniConnectionPoolManager poolMgr = new MiniConnectionPoolManager(dataSource, maxConnections);
...
Connection connection = poolMgr.getConnection();
...
connection.close();
But the documentation does not cover many things plus I am a beginner in using Database. My questions are:
When I am creating a new class that will need database connection to perform insert,update & other actions. Shall I pass the 'poolMgr' and call poolMgr.getConnection() from the newly created class?
When should I close this connection? I don't know for how long the bundle (user) will use the new class so shall I save the newly created connection in a private global variable and force the user to execute unregister class where I could then close the connection? Or shall I just close all connections when my database bundle is being deactivated.
Other suggestions are also appreciated to manage different classes accessing one database. Thank you in advance.
Edit:
The main class in my database bundle is always active as long as the application is running. It is the bundles requesting for an instance of a new class(performing database operation) that come and go. And also since it will be deployed in embedded system, I can only use small footprint applications.
You should get a connection from a connection pool when you need it and close the connection as soon as you can. It is the job of the connection pool to re-use connections, not yours.
In other words: Do not keep a connection alive until your consumer bundle is deactivated.
Connection pools normally implement DataSource interface, you should use the pools via it. In that case you can replace the pool implementation easily without changing your code. E.g:
#Component
public class MyComponent {
// Connection pool based DataSource
#Reference
DataSource dataSource;
public void myFunction() {
try (Connection c = dataSource.getConnection()) {
// Database operations
} catch (SQLException e) {
// TODO
}
}
}
When you find yourself repeating the same code many times (getting connection, catching SQLException), you can write a simple component that accepts functional interfaces. E.g.:
#Component
#Service
public class SQLHelper {
#Reference // This is a connection pool DataSource
private DataSource dataSource;
public <R> R execute(Callback<R> callback) {
try (Connection c = dataSource.getConnection()) {
return callback.call(c);
} catch (SQLException e) {
throw new UncheckedSQLException(e);
}
}
}
Your functional interface would look like this:
public interface Callback<R> {
R call(Connection connection);
}
And you would use it like this:
sqlHelper.execute((Connection c) -> {
// Do some stuff with the connection
});
Using transactions
If you want to use atomic transactions, I suggest that you should use org.apache.derby.jdbc.EmbeddedXADataSource together with org.apache.commons.dbcp.managed.BasicManagedDataSource from commons-dbcp. After that, you can handle transactions via JTA.
It is hard to use the JTA API directly. You should choose a library that helps you propagating transactions.
A small guide based on Declarative Services:
Install derby jar into your OSGi container
Install pax-derby bundle as well! By doing that, you will have a DataSourceFactory OSGi service
Install everit-dsf-bundle with its dependencies! You will see two new DS components. Create a configuration for the one called XADataSource via the webconsole! All configuration options have descriptions.
Install a JTA Transaction Manager into the OSGi container! You have several choices. I
Install everit-commons-dbcp-component with its dependencies! You will see two new DS components. Configure the Managed one in the webconsole and set the previously created XADataSource as the target! The transactional pool will take care of providing the same connection if you request-and-close connections whitin the scope of the same transaction.
normally use Aries Transaction Manager that embeds Geronimo TM.
Install everit-transaction-helper to your OSGi container! You will see a new OSGi service with the interface TransactionHelper (that is provided by a configurable DS component).
Now you have everything to write your code. Your component would similar to the following:
#Component
#Service
public class MyComponent {
#Reference
private DataSource dataSource;
#Reference
private TransactionHelper th;
public void myFunction() {
th.required(() -> {
try (Connection c = dataSource.getConnection()) {
// My SQL statements
} catch (SQLException e) {
// TODO
}
}
}
}
In case you do not need transaction handling, you can:
use the standard EmbeddedDataSource
use any non-transactional connection pool
skip the installation of the TransactionManager and TransactionHelper bundles
skip the usage of TransactionHelper from the code
A more complex guide (that also takes care of schema creation and uses OO based queries) is available at http://cookbook.everit.org/persistence/index.html.
Update
You do not have to get a connection for every SQL statement. You should get a connection, execute as many SQL statements that you can within a "moment" and than call close on the connection.
If you have to run three SQL statements right behind each other, you should request a connection, execute the three SQL statements and than call close on the connection
If you close the requested connection within the same function you requested it from the pool, you probably do things right. You might call other functions passing the connection as a parameter, but they should only use it to run SQL statements and than return.
You should not keep alive a connection and wait for another user action. That is the job of the connection pool. When you call close on a connection that is provided by a pool, the connection is not closed physically, but only retrieved to the pool.
You should keep the connection object in a local variable. If you use a member variable for your connection object, you should suspect that something is wrong with your code (the only exception is if you pass the Connection to an object that lives for a very short time and that object holds the connection in a member variable to have cleaner code).
Please note that if you use Java 6 or earlier, you should close the connection in a finally block to avoid unclosed connections.
MiniConnectionPoolManager might be a great solution for embedded devices as it is really "mini". The only issue is that it does not implement the DataSource interface so your business code shuold directly use the MiniCPM classes. By doing that, it will be much harder to switch to other Connection pool if you find a bug or you need a more complex pool later.
If you decide to use MiniCPM, I suggest that you should write a component that implements DataSource and delegates the getConnection() function to a MiniCPM instance. E.g.:
#Component
#Service
public class MiniCPMDataSourceComponent implements DataSource {
#Reference
protected ConnectionPoolDataSource cpDataSource;
private MiniConnectionPoolManager wrapped;
#Activate
public void activate() {
this.wrapped = new MiniConnectionPoolManager(cpDataSource);
}
#Override
public Connection getConnection() {
return wrapped.getConnection();
}
#Override
public Connection getConnection(String user, String password) {
throw new UnsupportedOperationException();
}
#Deactivate
public void deactivate() {
wrapped.dispose();
}
}
You can decorate this component with configuration possibilities like the max connection number and timeout (that is supported by MiniCPM). If you use the service that is provided by this component, you will be able to switch the connection pool without changing your business code. Also, your business bundle will not be wired directly to MiniCPM.
Good day, guys!
If I have non-transactional bean(BannerSizeServiceUntransact), which uses transactional bean(bannerSizeService), will Spring estabilish connection to DB, when I use non-transacional bean?
(I have many refused connections to PostgreSQL in log. I belive my logic does;t create new connection on each request, but may be I wrong.)
#Repository
public class BannerSizeServiceUntransactImpl implements BannerSizeServiceUntransact {
#Resource
BannerSizeService bannerSizeService;
public List<BannerSizeVO> sizesByType(String type) throws BannerServiceException{
return bannerSizeService.sizesByType(type);
} }
#Repository
#Transactional
public class BannerSizeServiceImpl implements BannerSizeService {
....
}
Yes, Spring will establish a database connection even when you're using beans that aren't marked #Transactional, so that's not the cause of your refused connections.
What's going to happen in this scenario is that when you invoke the call to bannerSizeService.sizesByType(type), Spring will start a new transaction, and when control returns to BannerSizeServiceUntransact.sizesByType(), it will end. So if BannerSizeServiceUntransact.sizesByType() did other database calls before or after the call to bannerSizeService.sizesByType(type), those calls would happen in separate transactions, one per DB call. (Not annotating a Service as #Transactional doesn't mean that transactions aren't used, just that they only span a single database call.)
Also note that if the method that calls BannerSizeServiceUntransact.sizesByType() was marked #Transactional, then the transaction started there will carry over all of the code you've shown here, because that transaction will start when that higher-up method is called and will end when it ends, and all of the code here will have executed while it was in effect. Not annotating something as #Transactional doesn't forbid its participation in an existing transaction, it just doesn't require the initiation of a new one.
Also, keep in mind that #Transactional controls transactions. Spring might end up making a new connection for each transaction it opens, or using only one and reusing it for each transaction, or rotating through a pool of connections (resulting in more than one but fewer than N connections for N transactions). It's guaranteed that if Spring talks to the database, there will be a connection in use, but you can't guarantee how many will be used over N calls simply by your #Transactional annotations. (Though of course you can set settings in your Spring config that might impact the number used, e.g. specifying a connection pool with a max size of 1.)
Spring supports programmatic transaction which give us fine grained control over TX management. According to Spring Documentation, One can use programmatic TX management by:
1. utilizing Spring's TransactionTemplate:
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
protected void doInTransactionWithoutResult(TransactionStatus status) {
try {
updateOperation1();
updateOperation2();
} catch (SomeBusinessExeption ex) {
status.setRollbackOnly();
}
} });
2. leveraging PlatformTransactionManager directly(inject a PlatformTransactionManager implementation into DAO):
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setName("SomeTxName");
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
//txManager is a reference to PlatformTransactionManager
TransactionStatus status = txManager.getTransaction(def);
try {
updateOperation1();
updateOperation2();
}
catch (MyException ex) {
txManager.rollback(status);
throw ex;
}
txManager.commit(status);
for the sake of simplification, let's say we are dealing with JDBC database operation.
I am wondering for any database operations happened at updateOperation1(),updateOperation2() in the second snippet, either it is implemented with JDBCTemplate or JDBCDaoSupport, if not, the operation is actually not performed within any transaction, is it?
My analysis is that if we don't use JDBCTemplate or JDBCDaoSupport, we inevitably will create/retrieve connection from datasource management. the connection we get is of course not the connection used by PlatformTransactionManager underlying to manage transaction.
I dug Spring source code and skim related class found that PlatformTransactionManager will try to retrieve a connection contained in ConnectionHolder which in return retrieved from TransactionSynchronizationManager. I also found JDBCTemplate and JDBCDaoSupport, also try to get connection with similar routine from TransactionSynchronizationManager.
Because TransactionSynchronizationManager manages many resource including connection per thread(basically use Threadlocal to ensure one thread get its own unique instance of the managed resource)
So I think the connection retrieved by PlatformTransactionManager and JDBCTemplate or JDBCDaoSupport is just same, this can explain how spring programmatic transaction ensure updateOperation1(),updateOperation2() were guarded by transaction.
Is my analysis correct? if it is, why Spring documentation hasn't emphasized this caveat?
Yes, it's correct.
Any code that uses raw Connections should obtain them from the DataSource in special way in order to participate in transactions managed by Spring (12.3.8 DataSourceTransactionManager):
Application code is required to retrieve the JDBC connection through DataSourceUtils.getConnection(DataSource) instead of Java EE's standard DataSource.getConnection.
Another option (if you cannot change code that calls getConnection()) is to wrap your DataSource with TransactionAwareDataSourceProxy.
I am trying to write some test cases for my DAO classes in a J2EE applications. Methods in my DAO classes try to get connection to the Database based on a JDBC URL (which is on the app server). So from the front end if I click bunch of stuff and make the DAO trigger it runs fine. However, when I write tests cases for the DAO and the DAO object calls the method then it is not able to get the connection to the database. I think since the JDBC resource is on the App server that is why it is not working from the test class.
because of this when I run my tests instead of pass or fail..it returns bunch of errors.
Has someone encountered this issue? what can I do to overcome this?
Example:
public class DBConnectionManager {
public static final String DB_URL = "jdbc/RSRC/my/connection/mydb"
public Connection getconnection ()
{
DataSource ds = ServiceLocator.getInstance().getDataSource(DB_URL);
return ds.getconnection();
}
}
public class MyDAO extends DBConnectionManager {
publci SomeBean getContents (String id)
{
Connection con = getConnection();
CallableStatement cs = con.prepareCall("{call myStorProc(?)}");
cs.setString(1, id);
...
//code to call resultset and retrieve SomeBean goes here
..
return SomeBean;
}
}
public class MyTests extends TestCase {
public testGetcontents ()
{
MyDAO myd = new MyDAO ();
SomeBean smb = myd.getContents("someparm");
assertEquals (5, smb.getSomeVal());
}
}
Should I be doing something extra in my testcase...? if so what?
EDIT:
error I get is:
java.lang.NoClassDefFoundError: com/iplanet/ias/admin/common/ASException
at java.lang.ClassLoader.defineClass1(Native Method)
Your DAO has a JNDI lookup string hard wired into it. Unless you have a JNDI lookup service available, it won't be able to get a connection.
I don't think a DAO should be responsible for acquiring a database connection. This design won't allow you to set transactions for a unit of work, because a DAO can't know if it's part of a larger unit of work.
I'd recommend passing the connection into the DAO, perhaps into its constructor. That way a service layer can establish appropriate transaction boundaries if there's more than one DAO in a single unit of work.
This design will have the added benefit of making it possible for your application to use its JNDI resource appropriately and your test to get its connection from a DriverManager, without having to use a JNDI lookup. You have two different sources for acquiring the DataSource or Connection - one for the app and another for the test.
UPDATE:
Here's what I mean, expressed in your code:
public class DBConnectionManager
{
public static final String DB_URL = "jdbc/RSRC/my/connection/mydb"
public Connection getConnection (String jndiLookup)
{
DataSource ds = ServiceLocator.getInstance().getDataSource(jndiLookup);
return ds.getconnection();
}
public Connection getConnection(String driver, String url, String username, String password)
throws ClassNotFoundException, SQLException
{
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
}
public class MyDAO
{
private Connection connection;
public MyDao(Connection connection)
{
this.connection = connection;
}
public SomeBean getContents (String id)
{
CallableStatement cs = this.connection.prepareCall("{call myStorProc(?)}");
this.connection.setString(1, id);
//code to call resultset and retrieve SomeBean goes here
return someBean;
}
}
You show nothing about closing resources properly or transactions. Judging by this code, you'll be in trouble on both counts. I'd think carefully about your implementation.
I'll recommend Spring JDBC to you. You can write your DAOs in Spring without rewriting your whole app.
I'll also point out that you might also be looking at generics: Don't Repeat The DAO.
Test well your ServiceLocator first. As you mentioned, the problem is probably because the datasource is declared on the server. Here the "bunch of errors" should be helpful, as of whether the problem is in acquiring the DataSource, or the Connectiion itself.
What database are you using? Can you logon to it from your machine from console? If not - configure it so that your host is allowed.
It could be a permissions issue on the database you're trying to access. What errors are you getting?
One useful way for testing database access is to create a clean, local "test" version of your database as part of your test harness. Before you run your tests, use scripts to create a local copy of the database with all the pertinent data, then run your tests against that, rather than the remote server.
People may argue that testing against a database in a unit test is not truly a unit test, since it has an external dependency. If you're able to refactor your DAO classes, you can make it so the actual data source is injectable through some interfaces. In your test code, you'd inject a "mock" data source which provides your test data in some in memory format, then in production, you'd use/inject the actual database source classes. If you can hide the external (non-business code related) parts of your DAO behind interfaces, you can use mocks in your unit tests to test more of your functionality, rather than the actual data access.
Where I work our DAOs have an injectable connection (via constructor injection), and we unit test against a mock connection. To test the code in the DAO, we pass in a mocked (usually using Mockito) connection, and set up expectations in our unit tests as to what methods will be called. This makes for somewhat noisy tests, as the tests look very similar to the code being developed, but it works for us.