1.创建DefaultObjectFactory的子类
package factory;
import java.util.List;
import java.util.Properties;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import tju.MyBtsBasic.domain.Book;
public class AmadeusObjectFactory extends DefaultObjectFactory{
String author;
static
{
System.out.println("in my diy object factory......");
}
@Override
public Object create(Class type) {
return super.create(type);
}
public Object create(Class type, List constructorArgTypes, List constructorArgs) {
Class<?> classToCreate = resolveInterface(type);
@SuppressWarnings("unchecked")
// we know types are assignable
Object created = super.create(classToCreate, constructorArgTypes, constructorArgs);
advice(created);
return created;
}
public void setProperties(Properties properties) {
author=properties.getProperty("author");
}
public Object advice(Object object)
{
if(Book.class.isAssignableFrom(object.getClass()))
{
Book b=(Book)object;
b.setAuthor(author);
}
return object;
}
}
2.配置自定义ObjectFactory
<?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">
<!-- XML 配置文件包含对 MyBatis 系统的核心设置 -->
<configuration>
<!-- 指定 MyBatis 所用日志的具体实现 -->
<properties resource="db.properties">
<property name="password" value="root"/>
</properties>
<settings>
<setting name="logImpl" value="LOG4J"/>
<!-- 要使延迟加载生效必须配置下面两个属性 -->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
<!--
<setting name="defaultExecutorType" value="BATCH"/>
-->
<setting name="defaultExecutorType" value="SIMPLE"/>
</settings>
<objectFactory type="factory.AmadeusObjectFactory">
<property name="author" value="liuxueyuan"/>
</objectFactory>
<environments default="mysql">
<!-- 环境配置,即连接的数据库。 -->
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="factory.c3p0DataSourceFactory">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/mybatis"/>
<property name="user" value="${username}"/>
<property name="password" value="${password}"/>
<property name="initialPoolSize" value="5"/>
<property name="maxPoolSize" value="20"/>
<property name="minPoolSize" value="5"/>
</dataSource>
</environment>
</environments>
<!-- mappers告诉了MyBatis去哪里找持久化类的映射文件 -->
<mappers>
<mapper class="tju.MyBtsBasic.mapper.BookMapper"/>
</mappers>
</configuration>