[背景]
jfinal的activeModel的model类默认提供了findFirst方法,一般的使用方法如下
employeePhotoFaceDao.findFirst("select * from employee_photo_face where id=?");使我不满意的是需要在sql中添加表名 employee_photo_face,能不能不添加这个表名呢?
[分析]
jfinal在启动是使用_MappingKit 建立的映射
public class _MappingKit {
public static void mapping(ActiveRecordPlugin arp) {
arp.addMapping("employee", "id", Employee.class);
arp.addMapping("employee_department", "id", EmployeeDepartment.class);
arp.addMapping("employee_group", "id", EmployeeGroup.class);
arp.addMapping("employee_photo_face", "id", EmployeePhotoFace.class);
arp.addMapping("employee_type", "id", EmployeeType.class);
arp.addMapping("sys_user", "id", SysUser.class);
}
}可以使用TableMapping.me().getTable(modelClass); 获取表名
剩下的就是泛型的问题了
[封装]
最终封装的代码如下
package com.litong.jfinal.service;
import com.jfinal.aop.Aop;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.TableMapping;
import com.litong.modules.face.recognize.common.model.EmployeePhotoFace;
/**
* @author litong
* @date 2020年9月29日_上午8:14:51
* @version 1.0
* @param <M>
* @desc
*/
public class ActiveRecoredService {
// 第一版
// public EmployeePhotoFace findFirst(String select, String where, Class<EmployeePhotoFace> class1) {
// return null;
// }
// 第二版
// public <T>T findFirst(String select, String where, Class<T> class1) {
// return null;
// }
// 第三版
// public <T> T findFirst(String select, String where, Class<? extends Model> class1) {
// return null;
// }
// 第 四 版
public <M extends Model<M>> M findFirst(String select, String where, Class<M> modelClass, Object... paras) {
Table table = TableMapping.me().getTable(modelClass);
M m = Aop.get(modelClass);
return m.findFirst(select + " " + "from " + table.getName() + " " + where, paras);
}
public static void main(String[] args) {
ActiveRecoredService activeRecoredService = Aop.get(ActiveRecoredService.class);
EmployeePhotoFace e = activeRecoredService.findFirst("select ", "where id=1", EmployeePhotoFace.class);
}
}测试
public void testModel() {
// ar 应 设置成类变量
ActiveRecoredService ar = Aop.get(ActiveRecoredService.class);
EmployeePhotoFace findFirst = ar.findFirst("select *", "where id=?", EmployeePhotoFace.class, 1);
JsonBean<EmployeePhotoFace> jsonBean = new JsonBean<>(findFirst);
renderJson(jsonBean);
}测试成功