zoukankan      html  css  js  c++  java
  • 第七章 使用 MyBatis API(MyBatis)

    使用 MyBatis-Spring,你可以继续直接使用 MyBatis 的 API。仅仅在代码中使用 Spring 中的 SqlSessionFactoryBean 来创建一个 SqlSessionFactory。

    public class UserMapperSqlSessionImpl implements UserMapper {
      // SqlSessionFactory would normally be set by SqlSessionDaoSupport
      private SqlSessionFactory sqlSessionFactory;
    
      public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
      }
    
      public User getUser(String userId) {
        // note standard MyBatis API usage - opening and closing the session manually
        SqlSession session = sqlSessionFactory.openSession();
    
        try {
          return (User) session.selectOne("org.mybatis.spring.sample.mapper.UserMapper.getUser", userId);
        } finally {
          session.close();
        }
      }
    }

    小心使用此选项, 因为错误的使用会产生运行时错误, 或者更糟糕的数据一致性的问题。这些是告诫:

    • 它不会参与到 Spring 的事务之中。

    • 如果 SqlSession 使用 DataSource,它也会被 Spring 事务管理器使用,而且当前有事务在进行时,这段代码会抛出异常。

    • MyBatis 的 DefaultSqlSession 是线程不安全的。如果在 bean 中注入了它,就会发生错误。

    • 使用 DefaultSqlSession 创建的映射器也不是线程安全的。如果你将它们注入到 bean 中,是会发生错误的。

    • 你必须保证在 finally 块中来关闭 SqlSession。

  • 相关阅读:
    Inside The C++ Object Model
    Inside The C++ Object Model
    奇偶剪枝算法
    HDU 1088 Write a simple HTML Browser
    HDU 1084 What Is Your Grade?
    二分图的最大匹配(匈牙利算法)HDU1083
    来自codeblock 贴吧
    HDU 1075 What Are You Taking About
    HDU 1082 Matrix Chain Multiplication
    pair模板类
  • 原文地址:https://www.cnblogs.com/shijiaoyun/p/4226104.html
Copyright © 2011-2022 走看看