1.问题描述
在项目中经常会有两个类存在一对多或者多对一的关联关系,这样在查询多的一方时,会深入查询关联的一方,而我们可能并不需要去深入查询那些数据,此时使用JsonConfig的jsonConfig.setExcludes过滤不需要转换的属性
2.举例
关联的类:
a:常用联系人
@Entity @Table(name = "core_contacts") public class Contacts implements java.io.Serializable{/** * 会员 */ private Member member; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "member") public Member getMember() { return member; } public void setMember(Member member) { this.member = member; } }
b:会员类
@Entity @Table(name = "core_member", uniqueConstraints = { @UniqueConstraint(columnNames = "user_account"), @UniqueConstraint(columnNames = "mobile"), @UniqueConstraint(columnNames = "email") }) public class Member implements java.io.Serializable {
//常用联系人 private Set<Contacts> contacts = new HashSet<Contacts>(0); public Member(Set<Contacts> contacts) { this.contacts = contacts; } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "member") public Set<Contacts> getContacts() { return contacts; } public void setContacts(Set<Contacts> contacts) { this.contacts = contacts; } }
3.在根据会员查询常用联系人时,会深入查询会员的所有信息,此时需要过滤
@RequestMapping("loadSelect.html") public JSONMessageView loadSelect(HttpServletRequest request){ JSONMessageView json=new JSONMessageView(BusinessConstant.ERR,"记载失败",null); Member member=super.getMember(); try { List<Contacts> contactPersonLst=contactsService.getByMember(member); if (contactPersonLst==null) { contactPersonLst=new ArrayList<Contacts>(); } Map<String, Object> map=new HashMap<String, Object>(); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setExcludes(new String[] { "member" });//过滤不需要转换的属性 JSONArray contactPersonList=JSONArray.fromObject(contactPersonLst,jsonConfig); map.put("contactPersonLst", contactPersonList); json.setCode(BusinessConstant.OK); json.setMessage("加载成功"); json.setContent(map); return json; } catch (Exception e) { e.printStackTrace(); json.setMessage("加载异常"); return json; }