RT麻烦详讲,最好有代码片段和配置文件片段,感谢!

解决方案 »

  1.   

    ibatis的事务如果封装的好的话,基本上是通过service来调用的。
      

  2.   

    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回滚
    文档里都有
      

  3.   

    如果我在Service是调用已写好的几个Dao方法, 如果把insert , update, delete 等需要事务控制的代码分散到几个DAO方法中,那么,我在通过一个Service方法将几个DAO方法组合起来时,如何控制这时的事务?
      

  4.   

    针对dao的几个方法相对来说是独立的,这样可以使用spring管理事务。但是spring针对的是单个方法的。
    如果你的数据库操作方法中又嵌套了别的数据库操作方法。那么直接用startTransaction就行了。
      

  5.   

    缺省情况下,调用SqlMapClient对象的任意executeXxxx()方法将缺省地自动COMMIT/ROLLBACK。这意味着每次调用executeXxxx()方法都是一个独立的事务。这确实很简单,但对于需要在同一个事务中执行多个语句的情况(即只能同时成功或失败),并不适用。这正是事务处理要关心的事情。
    如果您在使用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规范的资源),即同时成功或失败。
      

  6.   

    现在用 ibatis3, 确切的说应该要用 mybatis3 (这个ibatis这个方面不靠谱,名字都改了...)要如何控制呢? 有应用娴熟的大侠麻烦指点一二。同步看 Mybatis3-user-guide 中...
      

  7.   

    我的话都是从user-guide里抄来的。你不看???
      

  8.   

    这个还真不好弄,关键是不用改代码,把dao 的几个方法放在一个事务之中。 最不好的方法,是把那些代码放在写在一个事务里。
      

  9.   


    我是看阁下的回复似乎是旧版的内容。现在我看ibatis3
      

  10.   


    <cacheModel id=”productCache” type=”LRU”>  <flushInterval hours=”24”/>  <property name=”size” value=”1000” />  </cacheModel> 
    是这个??我也是才看。
      

  11.   

    我看的就是ibatis3的userguide啊你用的什么版本啊。还是别人已经封装过的?
      

  12.   

    http://dongwei.javaeye.com/blog/705519看,这篇文章最后用我的方法取得了SqlSession。然后用#3所说方法应该是没有问题的
      

  13.   

    SqlSession session = sqlSessionFactory.openSession(false); session.commit
    session.rollback
    不行?
      

  14.   


    想要service控制好几个dao里面的方法的话,可以用spring来设置。反正在spring里设置的时候,dao,service都可以设置为单例。这个是没有问题的。
      

  15.   

    spring 针对的是单个方法?你开什么玩笑!
      

  16.   

    我想讨论的是,抛开什么spring,就单纯 ibatis 本身实现。
      

  17.   

    一般都会用spring来管理的
    简单点儿的,直接用的话就下面这么用吧。
    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();
    }
    }
      

  18.   


    // 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;
    }
    }
      

  19.   

    事务是通过SqlSession控制,如果你想在Service层控制事务,那么要么你把SqlSession在Service层开启,然后通过参数传递,当然这不是好方法。
    另一中方法就是不要是使用DAO层,直接Service+IBATIS_Sql_Map.xml,然后在Service层开启事务,就能够在Service控制事务了。具体怎样配置,可以去看的javaeye博客http://lyb520320.javaeye.com/blog/586628
      

  20.   

    说说啊,诶,如果没有好的方法,就去弄回hibernate了。
      

  21.   

    代码片段:
    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文即可。
      

  22.   

    学习了   能不能给一个有关ibati+spring+struts2 的事物处理的例子呢?