[TOC]
问题描述
- mybatis逆向工程XXMapper.selectXX 方法会查询表所有字段,但是有时我们只需要某些字段
- 比如页面只需要json返回user表的id和name,但如果直接将XXMapper.selectXX查询的结果转化json返回,会不安全(里面还有password这些不想要页面看到的信息)
- 但是单表查询不想自己写sql和dao…
解决方案
在service层 只取需要的字段,封装到新对象,返回给action…
Code1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18public class UserServiceImpl implements UserService{
@Autowired
private SysUserMapper sysUserMapper;
public List<SysUser> findSysUserList(){
//从数据库查到的 含全部字段的 pojo
List<SysUser> old_sysUserList = sysUserMapper.findSysUserList()
//只取了需要的字段,封装到一个新的对象里
List<SysUser> my_sysUserList = (List<SysUser>)PojoUtils.convertToPojoByAddAttr(sysUserList,"name,id");
//返回的对象 只有name id 两个字段有值
return my_sysUserList;
}
}考虑到代码复用,将pojo转换过程封装为了工具类,这里用到反射机制。工具类代码如下
Code1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70package hw.utils;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class PojoUtils {
/**
* 描述: - 解决Mybatis逆向工程不能查特定字段的问题
* - 去掉不需要的字段的值
* 返回: 新的pojo,只含要求字段
*/
//返回有特定字段的类(SysUser)。输入有全部参数的实例(sysUser),和需要的属性名字"name"
public static Object convertToPojoByAddAttr(Object old_pojo, String attrNames) throws Exception{
Class clazz = old_pojo.getClass();
//创建新pojo
Constructor c = clazz.getConstructor(null);//取得无参构造函数
Object new_pojo = c.newInstance(null);//创建对象
String[] attrs = attrNames.split(",");
for(String attr_name: attrs){//attr是每一个字段的名字
String methodName = toMethodName("get",attr_name);//name变getName
Method method = clazz.getMethod(methodName);//get方法
Object attr_value = method.invoke(old_pojo);//得到属性的值
Class<?> returnType = method.getReturnType();//属性参数类型
//获得set方法
methodName = toMethodName("set",attr_name);//name变setName
method = clazz.getMethod(methodName,returnType);//set方法
//执行set方法给新pojo注值
method.invoke(new_pojo,attr_value);
}
return new_pojo;
}
/**
*
* 同上,只是针对查询结果为List的情况
*/
public static List<?> convertToPojoByAddAttr(List<?> old_pojo_list, String attrNames) throws Exception{
List<Object> new_pojo_list = new ArrayList<>();
for(Object old_pojo: old_pojo_list){
Object new_pojo = convertToPojoByAddAttr(old_pojo,attrNames);
new_pojo_list.add(new_pojo);
}
return new_pojo_list;
}
//name 变成 getName/setName toMethodName("set","name");
private static String toMethodName(String method,String attr){
char first_char = Character.toUpperCase(attr.charAt(0));
String rest_char = attr.substring(1);
StringBuilder stringBuilder = new StringBuilder().append(method).append(first_char).append(rest_char);
return stringBuilder.toString();
}
}




