The key component of MyBatis is SqlSessionFactory from which we get SqlSession and execute the mapped SQL statements. The SqlSessionFactory object can be created using XML-based configuration or Java API.

The most commonly used approach for building SqlSessionFactory is XML-based configuration. The following mybatis-config.xml file shows how a typical MyBatis configuration file looks:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration> <properties resource="application.properties">
<property name="username" value="db_user"/>
<property name="password" value="verysecurepwd"/>
</properties>
<settings>
<setting name="cacheEnabled" value="true"/>
</settings> <typeAliases>
<typeAlias alias="Tutor" type="com.mybatis3.domain.Tutor"/>
<package name="com.mybatis3.domain"/>
</typeAliases>
<typeHandlers>
<typeHandler handler="com.mybatis3.typehandlers.PhoneTypeHandler"/>
<package name="com.mybatis3.typehandlers"/>
</typeHandlers> <environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
<environment id="production">
<transactionManager type="MANAGED"/>
<dataSource type="JNDI">
<property name="data_source" value="java:comp/jdbc/MyBatisDemoDS"/>
</dataSource>
</environment>
</environments> <mappers>
<mapper resource="com/mybatis3/mappers/StudentMapper.xml"/>
<mapper url="file:///D:/mybatisdemo/mappers/TutorMapper.xml"/>
<mapper class="com.mybatis3.mappers.TutorMapper"/>
</mappers> </configuration>

Environment

MyBatis supports configuring multiple dataSource environments so that deploying the application in various environments, such as DEV, TEST, QA, UAT, and PRODUCTION, can be easily achieved by changing the default environment value to the desired environment id value. In the preceding configuration, the default environment has been set to development. When deploying the application on to production servers, you don't need to change the configuration much; just set the default environment to the production environment id attribute.

Sometimes, we may need to work with multiple databases within the same application. For example, we may have the SHOPPINGCART database to store all the order details and the REPORTS database to store the aggregates of the order details for reporting purposes.

If your application needs to connect to multiple databases, you'll need to configure each database as a separate environment and create a separate SqlSessionFactory object for each database.

<environments default="shoppingcart">
<environment id="shoppingcart">
<transactionManager type="MANAGED"/>
<dataSource type="JNDI">
<property name="data_source" value="java:comp/jdbc/ShoppingcartDS"/>
</dataSource>
</environment>
<environment id="reports">
<transactionManager type="MANAGED"/>
<dataSource type="JNDI">
<property name="data_source" value="java:comp/jdbc/ReportsDS"/>
</dataSource>
</environment>
</environments>

We can create SqlSessionFactory for a given environment as follows:

inputStream = Resources.getResourceAsStream("mybatis-config.xml");
defaultSqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
cartSqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream,"shoppingcart");
reportSqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream,"reports");

When we create SqlSessionFactory without explicitly defining environment id, SqlSessionFactory will be created using the default environment. In the preceding code, defaultSqlSessionFactory was created using the shoppingcart environment settings.

For each environment, we need to configure the dataSource and transactionManager elements.

DataSource

The dataSource element is used to configure the database connection properties.

<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>

The dataSource type can be one of the built-in types such as UNPOOLED, POOLED, or JNDI.

  • If you set the type to UNPOOLED, MyBatis will open a new connection and close that connection for every database operation. This method can be used for simple applications that have a small number of concurrent users.
  • If you set the type to POOLED, MyBatis will create a pool of database connections, and one of these connections will be used for the database operation. Once this is complete, MyBatis will return the connection to the pool. This is a commonly used method for developing/testing environments.
  • If you set the type to JNDI, MyBatis will get the connection from the JNDI dataSource that has typically been configured in the application server. This is a preferred method in production environments.

TransactionManager

MyBatis supports two types of transaction managers: JDBC and MANAGED.

The JDBC transaction manager is used where the application is responsible for managing the connection life cycle, that is, commit, rollback, and so on. When you set the TransactionManager property to JDBC, behind the scenes MyBatis uses the JdbcTransactionFactory class to create TransactionManager. For example, an application deployed on Apache Tomcat should manage the transactions by itself.

The MANAGED transaction manager is used where the application server is responsible for managing the connection life cycle. When you set the TransactionManager property to MANAGED, behind the scenes MyBatis uses the ManagedTransactionFactory class to create TransactionManager. For example, a JavaEE application deployed on an application server, such as JBoss, WebLogic, or GlassFish, can leverage the application server's transaction management capabilities using EJB. In these managed environments, you can use the MANAGED transaction manager.

MyBatis(3.2.3) - Configuring MyBatis using XML, Environment的更多相关文章

  1. MyBatis(3.2.3) - Configuring MyBatis using XML, typeHandlers

    As discussed in the previous chapter, MyBatis simplifies the persistent logic implementation by abst ...

  2. MyBatis(3.2.3) - Configuring MyBatis using XML, typeAliases

    In the SQL Mapper configuration file, we need to give the fully qualified name of the JavaBeans for ...

  3. MyBatis(3.2.3) - Configuring MyBatis using XML, Settings

    The default MyBatis global settings, which can be overridden to better suit application-specific nee ...

  4. MyBatis(3.2.3) - Configuring MyBatis using XML, Properties

    The properties configuration element can be used to externalize the configuration values into a prop ...

  5. MyBatis(3.2.3) - Configuring MyBatis using XML, Mappers

    Mapper XML files contain the mapped SQL statements that will be executed by the application using st ...

  6. Mybatis增加对象属性不增加mapper.xml的情况

    Mybatis增加对象属性不增加mapper.xml的情况: 只增加Model 对象的属性,在查询语句中返回相同名称的字段,但是在mapper中的 resultMap上面不进行新增字段的增加,查询结果 ...

  7. Mybatis学习总结(三)——SqlMapConfig.xml全局配置文件解析

    经过上两篇博文的总结,对mybatis中的dao开发方法和流程基本掌握了,这一节主要来总结一下mybatis中的全局配置文件SqlMapConfig.xml在开发中的一些常用配置,首先看一下该全局配置 ...

  8. Java Persistence with MyBatis 3(中文版) 第三章 使用XML配置SQL映射器

    关系型数据库和SQL是经受时间考验和验证的数据存储机制.和其他的ORM 框架如Hibernate不同,MyBatis鼓励开发者可以直接使用数据库,而不是将其对开发者隐藏,因为这样可以充分发挥数据库服务 ...

  9. Mybatis手工写sql语句及Mapper.xml方法

    首先在项目中 建一个mapper包,然后在spring集合mybatis的配置文件中设置扫描这个mapper包 然后,建 封装查询结果需要的 pojo 然后,在 mapper包中创建 Mapper接口 ...

随机推荐

  1. 用ALAssetsLibrary将过滤后图片写入照片库

    转载自:http://blog.sina.com.cn/s/blog_61235faa0100z3dp.html CIImage *saveToSave = [filter outputImage]; ...

  2. 转载LINQ系列OrderBy(), ThenBy()简介

    前言 前面两篇分别介绍了 Where() 与 Select() ,这篇则是要介绍 OrderBy() 与 ThenBy() ,这几个东西看起来最像 SQL 上会用到的语法,但切记一点,这边介绍的是 L ...

  3. quartz源码解析(一)

    本文的起因源于一次quartz的异常,在win2003正常运行的程序放在linux环境就抛出异常了,虽然找出异常没花我多长时间,不过由此加深了对quzrtz的了解:古人说,三折肱,为良医,说明经验对于 ...

  4. HttpContext讲解

    http://www.cnblogs.com/scy251147/p/3549503.html http://www.360doc.com/content/14/0526/10/17655805_38 ...

  5. Cocos2d-x——Cocos2d-x 屏幕适配新解【转载】

    Cocos2d-x 屏幕适配新解 本文出自[无间落叶](转载请保留出处):http://blog.leafsoar.com/archives/2013/05-10-19.html 为了适应移动终端的各 ...

  6. PostgreSQL的 initdb 源代码分析之十四

    继续分析: /* * Make the per-database PG_VERSION for template1 only after init'ing it */ write_version_fi ...

  7. Middleware课程01-概述

    中间件是一种独立的系统软件或服务程序,分布式应用软件借助这种软件在不同的技术之间共享资源.中间件位于客户机/ 服务器的操作系统之上,管理计算机资源和网络通讯.是连接两个独立应用程序或独立系统的软件.相 ...

  8. BZOJ 2208: [Jsoi2010]连通数 tarjan bitset

    2208: [Jsoi2010]连通数 Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://www.lydsy.com/JudgeOnline/pr ...

  9. [AngualrJS] ng-strict-di

    In Angular 1.5 introduces "compoment" syntax. But ng-annotate doesn't understand ".co ...

  10. 网络IPC:套接字之套接字描述符

    套接字是通信端点的抽象.与应用程序要使用文件描述符访问文件一样,访问套接字也需要套接字描述符.套接字描述符在UNIX系统是用文件描述符实现的.事实上,许多处理文件描述符的函数(如read和write) ...