基类 package com.future.common.base; import java.util.List; import java.util.Map; import com.jfinal.aop.Aop; import com.jfinal.plugin.activerecord.Model; import com.jfinal.plugin.activerecord.SqlPara; import cn.hutool.core.util.ClassUtil; /** * Dao类的基类,继承此类后能简化Dao层的代码 * 例如 * Dao中的代码是 * package com.test; * public class User{ * public SysUser getUser(String username){ * return find(username); * } * } * find(username)会去找key为 com.test.getUser的sql模板执行 * * * Model类型 * @param <T> */ @SuppressWarnings({ "unchecked", "rawtypes" }) public class BaseDao<T extends Model<T>> { /** * 获取model对象,此处不用DB是因为DB会在主数据源中查找sql,不适合多数据源的情况 */ private T t = (T) Aop.get(ClassUtil.getTypeArgument( getClass().getName().indexOf("$$EnhancerBy") == -1 ? getClass() : getClass().getSuperclass())); public List<T> find(Object... paras) { List<T> result = t.find(getSqlPara(paras)); return result; } public List<T> find(Map data) { List<T> result = t.find(getSqlPara(data)); return result; } public T findFirst(Object... paras) { return t.findFirst(getSqlPara(paras)); } public T findFirst(Map data) { return t.findFirst(getSqlPara(data)); } private SqlPara getSqlPara(Object... paras) { return this.t.getSqlPara(getsqlKey(), paras); } private SqlPara getSqlPara(Map data) { return this.t.getSqlPara(getsqlKey(), data); } /** * 获取sql模板的key,这里key的构成是Dao里面的packageName+className+"."+methodName * @return */ private String getsqlKey() { Class currentClass = getClass(); //不使用动态代理的情况也适用 Class useFullClass = currentClass.getName().indexOf("$$EnhancerBy") == -1 ? currentClass : currentClass.getSuperclass(); String className = useFullClass.getName(); String methodName = ""; StackTraceElement[] stacktraceItems = Thread.currentThread().getStackTrace(); for (StackTraceElement item : stacktraceItems) { if (item.getClassName().equals(className)) { methodName = item.getMethodName(); break; } } return className + "." + methodName; } }
在Dao中的用法
package com.future.dao; import com.future.common.base.BaseDao; import com.future.model.SysUser; public class SysUserDao extends BaseDao<SysUser>{ public SysUser findUserByUsername(String username) { return findFirst(username); } }
sql模板
#namespace("com.future.dao.SysUserDao") #sql("findUserByUsername") SELECT * FROM sys_user WHERE username = #para(0) #end #end
关注我的公众号,免费获取Java + Jfinal学习视频