框架之MyBatis核心配置

configuration 配置
-properties 属性
-settings 设置
-typeAliases 类型命名
-typeHandlers 类型处理器
-objectFactory 对象工厂
-plugins 插件
-environments 环境
--environment 环境变量
--transactionManager 事务管理器
-dataSource 数据源
-mappers 映射器


    
    
        
        

        
        

        
        
    

mapper.xml[insert、update、select、delete]



    
        INSERT INTO bill(ticketNum,ticketPrice,totalPrice,bookingID)
        VALUES (#{bookNum},#{price},#{price}*#{bookNum},#{bookingID})
    

    
        DELETE FROM bill where bookingID = #{bookingID}
    

    

核心对象

SqlSessionFactory

String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMapper(BlogMapper.class);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);

SqlSession

SqlSession session = sqlSessionFactory.openSession();

SqlSessionFactoryBuilder
这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了。
因此 SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)。
SqlSessionFactory
SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由对它进行清除或重建。
因此 SqlSessionFactory 的最佳作用域是应用作用域。有很多方法可以做到,最简单的就是使用单例模式或者静态单例模式。
SqlSession
每个线程都应该有它自己的 SqlSession 实例。SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。

动态SQL

  • if

    AND title like #{title}

  • choose (when, otherwise)

    
      AND title like #{title}
    
    
      AND author_name like #{author.name}
    
    
      AND featured = 1
    

  • trim (where, set)
 
    
         state = #{state}
     
    
        AND title like #{title}
    
    
        AND author_name like #{author.name}
    



  ... 


      username=#{username},
      password=#{password},
      email=#{email},
      bio=#{bio}



  ...

  • foreach

        #{item}

你可能感兴趣的:(框架之MyBatis核心配置)