SqlSessionFactory SqlSessionFactory has six methods that are used to create SqlSessionInstances. In general, the decisions you’ll be making when selecting one of these methods are: • Transaction: Do you want to use a transaction scope for the session, or use auto‐commit (usually means no transaction with most databases and/or JDBC drivers)? • Connection: Do you want iBATIS to acquire a Connection from the configured DataSource for you, or do you want to provide your own? • Execution: Do you want iBATIS to reuse PreparedStatements and/or batch updates (including inserts and deletes)? The set of overloaded openSession() method signatures allow you to choose any combination of these options that makes sense. SqlSession openSession() SqlSession openSession(boolean autoCommit) SqlSession openSession(Connection connection) SqlSession openSession(ExecutorType execType) SqlSession openSession(ExecutorType execType, boolean autoCommit) SqlSession openSession(ExecutorType execType, Connection connection) Configuration getConfiguration(); SqlSession As mentioned above, the SqlSession instance is the most powerful class in iBATIS. It is where you’ll find all of the methods to execute statements, commit or rollback transactions and acquire mapper instances. Thre are over twenty methods on the SqlSession class, so let’s break them up into more digestible groupings. Statement Execution Methods iBATIS 3 ‐ User Guide 12 August 2009 52 These methods are used to execute SELECT, INSERT, UPDATE and DELETE statements that are defined in your SQL Mapping XML files . They are pretty self explanatory, each takes the ID of the statement and the Parameter Object, which can be a primitive (auto‐boxed, or wrapper), a JavaBean, a POJO or a Map. Object selectOne(String statement, Object parameter) List selectList(String statement, Object parameter) int insert(String statement, Object parameter) int update(String statement, Object parameter) int delete(String statement, Object parameter) B ecause not all statements require a parameter, these methods are overloaded with versions that do not require the parameter object. Object selectOne(String statement) List selectList(String statement) int insert(String statement) int update(String statement) int delete(String statement) Finally, there are three advanced versions of the select methods that allow you to restrict the range of rows to return, or provide custom result handling logic, usually for very large data sets. List selectList (String statement, Object parameter, int offset, int limit) void select (String statement, Object parameter, ResultHandler handler) void select (String statement, Object parameter, int offset, int limit, ResultHandler handler) Transaction Control Methods There are four methods for controlling the scope of a transaction. Of course, these have no effect if you’ve chosen to use auto‐commit or if you’re using an external transaction manager. However, if you’re using the JDBC transaction manager, managed by the Connection instance, then the four methods that will come in handy are: void commit() void commit(boolean force) void rollback() void rollback(boolean force)意思就是说,在SqlSessionFactory.openSession这里传入false,让事务设置成不自动提交 然后SqlSession.commit提交,SqlSession.rollback回滚 文档里都有
SqlSessionFactory has six methods that are used to create SqlSessionInstances. In general, the decisions
you’ll be making when selecting one of these methods are:
• Transaction: Do you want to use a transaction scope for the session, or use auto‐commit
(usually means no transaction with most databases and/or JDBC drivers)?
• Connection: Do you want iBATIS to acquire a Connection from the configured DataSource for
you, or do you want to provide your own?
• Execution: Do you want iBATIS to reuse PreparedStatements and/or batch updates (including
inserts and deletes)?
The set of overloaded openSession() method signatures allow you to choose any combination of these
options that makes sense.
SqlSession openSession()
SqlSession openSession(boolean autoCommit)
SqlSession openSession(Connection connection)
SqlSession openSession(ExecutorType execType)
SqlSession openSession(ExecutorType execType, boolean autoCommit)
SqlSession openSession(ExecutorType execType, Connection connection)
Configuration getConfiguration();
SqlSession
As mentioned above, the SqlSession instance is the most powerful class in iBATIS. It is where you’ll find
all of the methods to execute statements, commit or rollback transactions and acquire mapper
instances.
Thre are over twenty methods on the SqlSession class, so let’s break them up into more digestible
groupings.
Statement Execution Methods
iBATIS 3 ‐ User Guide
12 August 2009 52
These methods are used to execute SELECT, INSERT, UPDATE and DELETE statements that are defined in
your SQL Mapping XML files . They are pretty self explanatory, each takes the ID of the statement and
the Parameter Object, which can be a primitive (auto‐boxed, or wrapper), a JavaBean, a POJO or a Map.
Object selectOne(String statement, Object parameter)
List selectList(String statement, Object parameter)
int insert(String statement, Object parameter)
int update(String statement, Object parameter)
int delete(String statement, Object parameter)
B
ecause not all statements require a parameter, these methods are overloaded with versions that do
not require the parameter object.
Object selectOne(String statement)
List selectList(String statement)
int insert(String statement)
int update(String statement)
int delete(String statement)
Finally, there are three advanced versions of the select methods that allow you to restrict the range of
rows to return, or provide custom result handling logic, usually for very large data sets.
List selectList
(String statement, Object parameter, int offset, int limit)
void select
(String statement, Object parameter, ResultHandler handler)
void select
(String statement, Object parameter, int offset, int limit,
ResultHandler handler)
Transaction Control Methods
There are four methods for controlling the scope of a transaction. Of course, these have no effect if
you’ve chosen to use auto‐commit or if you’re using an external transaction manager. However, if
you’re using the JDBC transaction manager, managed by the Connection instance, then the four
methods that will come in handy are:
void commit()
void commit(boolean force)
void rollback()
void rollback(boolean force)意思就是说,在SqlSessionFactory.openSession这里传入false,让事务设置成不自动提交
然后SqlSession.commit提交,SqlSession.rollback回滚
文档里都有
如果你的数据库操作方法中又嵌套了别的数据库操作方法。那么直接用startTransaction就行了。
如果您在使用Global Transaction(在SQL Map配置文件中设置),您可以使用自动提交并且可以得到在同一事务中执行的效果。但为了提高性能,最好是明确地划分事务的范围,因为这样做可以减少连接池的通讯流量和数据库连接的初始化。
SqlMapClient对象拥有让您定义事务范围的方法。使用下面SqlMapClient类的方法,可以开始、提交和/或回退事务:
public void startTransaction () throws SQLException
public void commitTransaction () throws SQLException
public void endTransaction () throws SQLException
开始一个事务,意味着您从连接池中得到一个连接,打开它并执行查询和更新SQL操作。使用事务处理的例子如下:
http://www.ibatis.com Clinton Begin 著 刘涛([email protected]) 译
开发指南 iBATIS SQLMaps Page 47 of 62
private Reader reader = new Resources.getResourceAsReader(
"com/ibatis/example/sqlMapconfig.xml");
private SqlMapClient sqlMap = XmlSqlMapBuilder.buildSqlMap(reader);
public updateItemDescription (String itemId, String newDescription) throws SQLException {
try {
sqlMap.startTransaction ();
Item item = (Item) sqlMap.queryForObject ("getItem", itemId);
item.setDescription (newDescription);
sqlMap.update ("updateItem", item);
sqlMap.commitTransaction ();
} finally {
sqlMap.endTransaction ();
}
}
注意!事务不能嵌套。在调用commit()或rollback()之前,从同一线程多次调用.startTransaction,将引起抛出例外。换句话说,对于每个SqlMap实例,每个线程最多只能打开一个事务。
注意!SqlMapClient事务处理使用Java的ThreadLocal保存事务对象。这意味着在处理事务时,每个调用startTransaction()的线程,将得到一个唯一的Connection对象。将一个Connection对象返回数据源(或关闭连接)唯一的方法是调用commitTransaction()或rollbackTransaction()方法。否则,会用光连接池中的连接并导致死锁。
自动的事务处理
虽然极力推荐使用明确划分的事务范围,在简单需求(通常使只读)的情况下,可以使用简化的语法。如果您没有使用startTransaction(),commitTransation()和rollbackTransaction()方法来明确地划分事务范围,事务将会自动执行。例如:
private Reader reader = new Resources.getResourceAsReader
("com/ibatis/example/sqlMapconfig.xml");
private SqlMapClient sqlMap = XmlSqlMapBuilder.buildSqlMap(reader);
public updateItemDescription (String itemId, String newDescription) throws SQLException {
try {
Item item = (Item) sqlMap.queryForObject ("getItem", itemId);
item.setDescription (“TX1”);
//No transaction demarcated, so transaction will be automatic (implied)
sqlMap.update ("updateItem", item);
item.setDescription (newDescription);
item.setDescription (“TX2”);
//No transaction demarcated, so transaction will be automatic (implied)
sqlMap.update("updateItem", item);
http://www.ibatis.com Clinton Begin 著 刘涛([email protected]) 译
开发指南 iBATIS SQLMaps Page 48 of 62
} catch (SQLException e) {
throw (SQLException) e.fillInStackTrace();
}
}
注意!使用自动事务处理要非常小心。虽然看起来很有吸引力,但如果有多个数据更新操作要在同一事务中处理时,您会遇到麻烦。在上面的例子中,如果第二个“updateItem”操作失败,第一个“updateItem”操作仍然会执行,description会更新成“TX1”。
全局(分布式)事务
SQL Map框架支持全局事务。全局事务也叫分布式事务,它可以允许您在同一事务中更新多个数据库(或其他符合JTA规范的资源),即同时成功或失败。
我是看阁下的回复似乎是旧版的内容。现在我看ibatis3
<cacheModel id=”productCache” type=”LRU”> <flushInterval hours=”24”/> <property name=”size” value=”1000” /> </cacheModel>
是这个??我也是才看。
session.rollback
不行?
想要service控制好几个dao里面的方法的话,可以用spring来设置。反正在spring里设置的时候,dao,service都可以设置为单例。这个是没有问题的。
简单点儿的,直接用的话就下面这么用吧。
public void delArticles(String[] ids) {
SqlSession session = MyBatisUtil.getSession();
try {
for(String id:ids){
session.delete(Article.class.getName()+".del", Integer.parseInt(id));
session.delete(Article.class.getName()+".del_channel_article", Integer.parseInt(id));
}
//提交事务
session.commit();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
} finally{
//关闭session
session.close();
}
}
// SqlSession对象
mSession = ServiceStatic.mSqlMapper.openSession(TransactionIsolationLevel.READ_COMMITTED);
// 业务处理层,实现对应业务处理
try
{
N_SEC_USERControl.f_insertN_SEC_USER(mSession, gp);
mSession.commit();
// log4j日志记录器
mlogger.info(mLogTitle + "插入N_SEC_USER数据成功.");
}
catch (Exception exp)
{
mSession.rollback();
// log4j日志记录器
String errmsg=mLogTitle + "插入N_SEC_USER数据失败!" + exp.getMessage();
mlogger.error(errmsg);
throw exp;
}
finally
{
if (mSession != null)
{
// 关闭SqlSession对象
mSession.close();
mSession = null;
}
}
另一中方法就是不要是使用DAO层,直接Service+IBATIS_Sql_Map.xml,然后在Service层开启事务,就能够在Service控制事务了。具体怎样配置,可以去看的javaeye博客http://lyb520320.javaeye.com/blog/586628
public static void main(String[] args){
SqlSessionFactory sessonFactory = Tools.getSqlSessionFactory();
SqlSession session = sessonFactory.openSession();
try{
NmsServiceMapper mapper = session.getMapper(NmsServiceMapper.class);//NmsServiceMapper为接口,接口中声明了与配置文件中一致的方法
MailServiceMapper mailM = session.getMapper(MailServiceMapper.class);
MailMtBean mb = new MailMtBean();
mb.setContent("");////给bean赋值
NmsMtBean nb = new NmsMtBean();
nb.setNms_phoneno("13811111111");
mapper.insertNmsMt(nb);
mailM.insertMailMt(mb);
session.commit();
}catch(Exception e){
session.rollback();
e.printStackTrace();
}finally{
session.close();
}
}配置文件:
通过Mapper的方式影射sql文即可。