objectFactory

Each time MyBatis creates a new instance of a result object, it uses an ObjectFactory instance to do so. The default ObjectFactory does little more than instantiate the target class with a default constructor, or a parameterized constructor if parameter mappings exist. If you want to override the default behaviour of the ObjectFactory, you can create your own. For example:

  1. // ExampleObjectFactory.java
  2. public class ExampleObjectFactory extends DefaultObjectFactory {
  3. @Override
  4. public <T> T create(Class<T> type) {
  5. return super.create(type);
  6. }
  7. @Override
  8. public <T> T create(Class<T> type, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
  9. return super.create(type, constructorArgTypes, constructorArgs);
  10. }
  11. @Override
  12. public void setProperties(Properties properties) {
  13. super.setProperties(properties);
  14. }
  15. @Override
  16. public <T> boolean isCollection(Class<T> type) {
  17. return Collection.class.isAssignableFrom(type);
  18. }
  19. }
  1. <!-- mybatis-config.xml -->
  2. <objectFactory type="org.mybatis.example.ExampleObjectFactory">
  3. <property name="someProperty" value="100"/>
  4. </objectFactory>

The ObjectFactory interface is very simple. It contains two create methods, one to deal with the default constructor, and the other to deal with parameterized constructors. Finally, the setProperties method can be used to configure the ObjectFactory. Properties defined within the body of the objectFactory element will be passed to the setProperties method after initialization of your ObjectFactory instance.