通常我们会使用mybatis-generator生成条件查询的相关criteria对象,但是每次写条件查询的时候都要去new这么一个对象,非常浪费内存空间,所以可以写一个单例工厂用于创建相关的criteria对象。
未使用单例工厂之前的会写类似这样的代码:
InvoiceCriteria invoiceCriteria = new InvoiceCriteria();
//InvoiceCriteria invoiceCriteria = CriteriaFactory.createCriteria(InvoiceCriteria.class);
System.out.println(invoiceCriteria);
Criteria criteria = invoiceCriteria.createCriteria();
使用单例工厂之后会使得每次拿到的criteria对象都是同一个对象:
//InvoiceCriteria invoiceCriteria = new InvoiceCriteria();
InvoiceCriteria invoiceCriteria = CriteriaFactory.createCriteria(InvoiceCriteria.class);
System.out.println(invoiceCriteria);
Criteria criteria = invoiceCriteria.createCriteria();
具体实现如下,首先让mybatis-generator自动生成的criteria对象实现一个统一的接口,如CbpsCriteria,这个接口相当于一个标记接口,无需定义任何方法。
package top.auok.cbps.ssm.ps.factory;
public interface CbpsCriteria {
}
import top.auok.cbps.ssm.ps.factory.CbpsCriteria;
public class InvoiceCriteria implements CbpsCriteria {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public InvoiceCriteria() {
oredCriteria = new ArrayList<Criteria>();
}
......
单例工厂代码如下:
package top.auok.cbps.ssm.ps.factory;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
/**
* mybatis criteria singleton factory
*
* @author leocnx
*
*/
public class CriteriaFactory {
private static final Map<String, Object> objectMap = new HashMap<String, Object>();
@SuppressWarnings({ "rawtypes", "unchecked" })
public synchronized static <T extends CbpsCriteria> T createCriteria(Class<T> c) {
CbpsCriteria cbpsCriteria = null;
String className = null;
className = c.getName();
try {
if (!objectMap.containsKey(className)) {
Class clazz = Class.forName(className);
// 获得无参构造
Constructor constructor = clazz.getDeclaredConstructor();
// 设置无参构造是可访问的
constructor.setAccessible(true);
// 产生一个实例对象
cbpsCriteria = (CbpsCriteria) constructor.newInstance();
objectMap.put(className, cbpsCriteria);
}
} catch (Exception e) {
e.printStackTrace();
}
return (T) objectMap.get(className);
}
}
the end.