| A thread safe client for working with your SQL Maps (Start Here). This interface inherits transaction control
and execution methods from the SqlMapTransactionManager and SqlMapExecutor interfaces.
The SqlMapClient is the central class for working with SQL Maps. This class will allow you
to run mapped statements (select, insert, update, delete etc.), and also demarcate
transactions and work with batches. Once you have an SqlMapClient instance, everything
you need to work with SQL Maps is easily available.
The SqlMapClient can either
be worked with directly as a multi-threaded client (internal session management), or you can get a single threaded
session and work with that. There may be a slight performance increase if you explicitly
get a session (using the openSession() method), as it saves the SqlMapClient from having
to manage threads contexts. But for most cases it won't make much of a difference, so
choose whichever paradigm suits your needs or preferences.
An SqlMapClient instance can be safely made static or applied as a Singleton.
Generally it's a good idea to make a simple configuration class that will configure the
instance (using SqlMapClientBuilder) and provide access to it.
The following example will demonstrate the use of SqlMapClient.
//
// autocommit simple query --these are just examples...not patterns
//
Employee emp = (Employee) sqlMap.queryForObject("getEmployee", new Integer(1));
//
// transaction --these are just examples...not patterns
//
try {
sqlMap.startTransaction()
Employee emp2 = new Employee();
// ...set emp2 data
Integer generatedKey = (Integer) sqlMap.insert ("insertEmployee", emp2);
emp2.setFavouriteColour ("green");
sqlMap.update("updateEmployee", emp2);
sqlMap.commitTransaction();
} finally {
sqlMap.endTransaction();
}
//
// session --these are just examples...not patterns
//
try {
SqlMapSession session = sqlMap.openSession()
session.startTransaction()
Employee emp2 = new Employee();
// ...set emp2 data
Integer generatedKey = (Integer) session.insert ("insertEmployee", emp2);
emp2.setFavouriteColour ("green");
session.update("updateEmployee", emp2);
session.commitTransaction();
} finally {
try {
session.endTransaction();
} finally {
session.close();
}
// Generally your session scope would be in a wider context and therefore the
// ugly nested finally block above would not be there. Realize that sessions
// MUST be closed if explicitly opened (via openSession()).
}
//
// batch --these are just examples...not patterns
//
try {
sqlMap.startTransaction()
List list = (Employee) sqlMap.queryForList("getFiredEmployees", null);
sqlMap.startBatch ();
for (int i=0, n=list.size(); i < n; i++) {
sqlMap.delete ("deleteEmployee", list.get(i));
}
sqlMap.executeBatch();
sqlMap.commitTransaction();
} finally {
sqlMap.endTransaction();
}
See Also: SqlMapClientBuilder See Also: SqlMapSession See Also: SqlMapExecutor |