mybatis对象工厂(objectFactory)
程序员文章站
2022-07-15 10:24:46
...
MyBatis 每次创建结果对象的新实例时,它都会使用一个对象工厂(ObjectFactory)实例来完成。 默认的对象工厂需要做的仅仅是实例化目标类,要么通过默认构造方法,要么在参数映射存在的时候通过参数构造方法来实例化。 如果想覆盖对象工厂的默认行为,则可以通过创建自己的对象工厂来实现。比如:
import com.hhz.entity.User;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
public class MyObjcetFactory extends DefaultObjectFactory {
@Override
public Object create(Class type) {
if (User.class == type) {
User user = (User) super.create(type);
// 给每个user对象的address属性设置为CHINA
user.setAddress("CHINA");
return user;
}
return super.create(type);
}
}
使用方法:
mybatis-config.xml中:
<?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="config.properties"/>
<objectFactory type="com.hhz.util.MyObjcetFactory"/>
<environments default="dev">
<environment id="dev">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.hhz.dao"/>
</mappers>
</configuration>
测试以及结果:
@Test
public void listTest(){
UserMapper dao = sqlSession.getMapper(UserMapper.class);
List<User> list = dao.list();
System.out.println(list);
}
日志:
[DEBUG] ==> Preparing: select * from user
[DEBUG] ==> Parameters:
[DEBUG] <== Total: 4
[User{id=1, username='花花', age=20, sex=false, address='CHINA'}, User{id=2, username='点点', age=30, sex=true, address='CHINA'}, User{id=3, username='yuanyuan', age=25, sex=true, address='CHINA'}, User{id=5, username='品牌', age=35, sex=false, address='CHINA'}]
上一篇: 轻松搞定AOP