Mybatis配置文件分析
来源:互联网 发布:济南行知小学学区划分 编辑:程序博客网 时间:2024/05/22 14:47
Mybatis配置文件分析
Configuration
properties说明
<properties resource="org/mybatis/example/config.properties"> <property name="username" value="dev_user"/> <property name="password" value="F2Fa3!33TYyg"/></properties>
数据库的配置肯定也是可以配置在外部文件的,如上面代码所示,配置在org/mybatis/example/config.properties文件中。然后在XML配置文件中引用,引用方式如下:
<dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/></dataSource>
settings说明
TypeAliases
这个可以设置类的别名,如下:
<typeAliases> <typeAlias alias="Author" type="domain.blog.Author"/> <typeAlias alias="Blog" type="domain.blog.Blog"/> <typeAlias alias="Comment" type="domain.blog.Comment"/> <typeAlias alias="Post" type="domain.blog.Post"/> <typeAlias alias="Section" type="domain.blog.Section"/> <typeAlias alias="Tag" type="domain.blog.Tag"/></typeAliases>
上面是XML的指定,也可以使用注解的方式来设置:
先设置哪些包将用于扫描,获得注解的bean
<typeAliases> <package name="domain.blog"/></typeAliases>
然后在要设置别名的类上注解别名:
@Alias("author")public class Author { ...}
typeHandlers 的作用是将Java类型与数据库中类型进行匹配,在statement设值和ResultSet检索值时可以正确的转换,可以实现TypeHandler接口实现自己的类型处理器。mybatis中内建的类型处理器(Type Handler )
当然,我们也可以实现我们自己的类型转化器:
@MappedJdbcTypes(JdbcType.VARCHAR)public class ExampleTypeHandler extends BaseTypeHandler<String> { @Override public void setNonNullParameter(PreparedStatement ps, int i, String parameter, Jd ps.setString(i, parameter); } @Override public String getNullableResult(ResultSet rs, String columnName) throws SQLExcept return rs.getString(columnName); } @Override public String getNullableResult(ResultSet rs, int columnIndex) throws SQLExceptio return rs.getString(columnIndex); } @Override public String getNullableResult(CallableStatement cs, int columnIndex) throws SQL return cs.getString(columnIndex); }}
然后在配置文件中引入:
<!-- mybatis-config.xml --><typeHandlers> <typeHandler handler="org.mybatis.example.ExampleTypeHandler"/></typeHandlers>
ObjectFactory
查询结果映射成java类的时候,java对象实例是通过ObjectFactory来初始化生成的。默认的objectFactory包含默认构造函数的和带参数构造函数的初始化,我们也可以通过集成DefaultObjectFactory来重写:
public class ExampleObjectFactory extends DefaultObjectFactory { public Object create(Class type) { return super.create(type); } public Object create(Class type, List<Class> constructorArgTypes, List<Object> co return super.create(type, constructorArgTypes, constructorArgs); } public void setProperties(Properties properties) { super.setProperties(properties); }}
然后在配置文件中引入:
<!-- mybatis-config.xml --><objectFactory type="org.mybatis.example.ExampleObjectFactory"> <property name="someProperty" value="100"/></objectFactory>
environment
支持在不同环境下,使用不同数据库配置。
注意:每个SqlSessionFactory只能对应使用一个配置。
<environments default="development"> <environment id="development"> <transactionManager type="JDBC"> <property name="..." value="..."/> </transactionManager> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment></environments>
上面的代码设置了一个environment,并且设置为默认的环境。
事物的管理有两种,一种是上面的JDBC另一种是MANAGED。
JDBC:简单的使用了JDBC的事物提交和回滚机制。
MANAGED:不做任何事情,默认情况下会关闭连接。为了使用别的东西来管理事务,需要关闭这个机制
<transactionManager type="MANAGED"> <property name="closeConnection" value="false"/></transactionManager>
JDBC和MANAGED是两种事务管理的别名,如果你想取代这两种事务管理,可以自己实现两个事务管理接口,并且type上写上TransactionFactory实现类的全名。
要想实现自己的事务管理,必须实现两个接口一个是TransactionFactory,另一个是Transaction,我们来看一下JDBC事务管理是如何实现的:
TransactionFactory实现类
public class JdbcTransactionFactory implements TransactionFactory { public void setProperties(Properties props) { } public Transaction newTransaction(Connection conn) { return new JdbcTransaction(conn); } public Transaction newTransaction(DataSource ds, TransactionIsolationLevel level, boolean autoCommit) { return new JdbcTransaction(ds, level, autoCommit); }}
Transaction实现类:
/** * {@link Transaction} that makes use of the JDBC commit and rollback facilities directly. * It relies on the connection retrieved from the dataSource to manage the scope of the transaction. * Delays connection retrieval until getConnection() is called. * Ignores commit or rollback requests when autocommit is on. * * @see JdbcTransactionFactory */public class JdbcTransaction implements Transaction { private static final Log log = LogFactory.getLog(JdbcTransaction.class); protected Connection connection; protected DataSource dataSource; protected TransactionIsolationLevel level; protected boolean autoCommmit; public JdbcTransaction(DataSource ds, TransactionIsolationLevel desiredLevel, boolean desiredAutoCommit) { dataSource = ds; level = desiredLevel; autoCommmit = desiredAutoCommit; } public JdbcTransaction(Connection connection) { this.connection = connection; } public Connection getConnection() throws SQLException { if (connection == null) { openConnection(); } return connection; } public void commit() throws SQLException { if (connection != null && !connection.getAutoCommit()) { if (log.isDebugEnabled()) { log.debug("Committing JDBC Connection [" + connection + "]"); } connection.commit(); } } public void rollback() throws SQLException { if (connection != null && !connection.getAutoCommit()) { if (log.isDebugEnabled()) { log.debug("Rolling back JDBC Connection [" + connection + "]"); } connection.rollback(); } } public void close() throws SQLException { if (connection != null) { resetAutoCommit(); if (log.isDebugEnabled()) { log.debug("Closing JDBC Connection [" + connection + "]"); } connection.close(); } } protected void setDesiredAutoCommit(boolean desiredAutoCommit) { try { if (connection.getAutoCommit() != desiredAutoCommit) { if (log.isDebugEnabled()) { log.debug("Setting autocommit to " + desiredAutoCommit + " on JDBC Connection [" + connection + "]"); } connection.setAutoCommit(desiredAutoCommit); } } catch (SQLException e) { // Only a very poorly implemented driver would fail here, // and there's not much we can do about that. throw new TransactionException("Error configuring AutoCommit. " + "Your driver may not support getAutoCommit() or setAutoCommit(). " + "Requested setting: " + desiredAutoCommit + ". Cause: " + e, e); } } protected void resetAutoCommit() { try { if (!connection.getAutoCommit()) { // MyBatis does not call commit/rollback on a connection if just selects were performed. // Some databases start transactions with select statements // and they mandate a commit/rollback before closing the connection. // A workaround is setting the autocommit to true before closing the connection. // Sybase throws an exception here. if (log.isDebugEnabled()) { log.debug("Resetting autocommit to true on JDBC Connection [" + connection + "]"); } connection.setAutoCommit(true); } } catch (SQLException e) { log.debug("Error resetting autocommit to true " + "before closing the connection. Cause: " + e); } } protected void openConnection() throws SQLException { if (log.isDebugEnabled()) { log.debug("Openning JDBC Connection"); } connection = dataSource.getConnection(); if (level != null) { connection.setTransactionIsolation(level.getLevel()); } setDesiredAutoCommit(autoCommmit); } }
我们可以看到JdbcTransactionFactory只是用来获得一个实际管理事务的JDBCransaction。而JdbcTransaction则实现了获得连接,事务提交|事务回滚,关闭连接等操作。看了上面的例子,自己重新写一个应该知道怎么写了把。
dataSource
定义了Unpooled不带连接池的,每次都简单的创建和关闭,这种性能低
POOLED带连接池的,JNDI使用外部定义的。
Mappers
Mapper用来定义sql语句,而mappers就是用来引入mapper映射文件。
XML配置方式:
<!-- Using classpath relative resources --><mappers> <mapper resource="org/mybatis/builder/AuthorMapper.xml"/> <mapper resource="org/mybatis/builder/BlogMapper.xml"/> <mapper resource="org/mybatis/builder/PostMapper.xml"/></mappers>
<!-- Using url fully qualified paths --><mappers> <mapper url="file:///var/mappers/AuthorMapper.xml"/> <mapper url="file:///var/mappers/BlogMapper.xml"/> <mapper url="file:///var/mappers/PostMapper.xml"/></mappers>
注解的方式:
<!-- Using mapper interface classes --><mappers> <mapper class="org.mybatis.builder.AuthorMapper"/> <mapper class="org.mybatis.builder.BlogMapper"/> <mapper class="org.mybatis.builder.PostMapper"/></mappers>
<!-- Register all interfaces in a package as mappers --><mappers> <package name="org.mybatis.builder"/></mappers>
© Programmer's life_海舰. Themed by WheatV Themes. Powered by 点点网
- Mybatis配置文件分析
- Mybatis配置文件记录与分析
- Mybatis源码分析(一)- Configuration配置文件详解
- MyBatis知识四 全局配置文件SqlMapConfig 分析
- MyBatis源码分析:如何解析配置文件
- Mybatis配置文件(mybatis-config.xml )源码分析
- MyBatis配置文件
- mybatis 配置文件
- mybatis配置文件
- mybatis 配置文件
- MyBatis配置文件
- Mybatis配置文件
- mybatis配置文件
- mybatis配置文件
- mybatis配置文件
- mybatis配置文件
- mybatis配置文件
- mybatis配置文件
- GHJSFGFAFDDSGFDHGFDHFHY7567
- mybatis注解详解
- mybatis与spring整合(基于配置文件)
- 基于注解的mybatis和spring整合
- MyBatis多参数传递之注解方式示例
- Mybatis配置文件分析
- spring与mybatis三种整合方法
- Spring MVC 框架搭建及详解
- MyBatis+Spring 基于接口编程的原理分析
- Volley.jar 制作方法
- 最长回文子串
- DirectX 9.0c游戏开发手记之“龙书”第二版学习笔记之7: Chap9: Color
- Reverse words
- 算法学习之排序算法:插入排序(直接插入排序、折半插入排序、2-路插入排序)