使用JPA的时候,在使用它和手机端进行交互的时候常常遇到只要某几个字段,但是会全部拿到的情况, 如:
拿到某个用户的全部信息, 如果这个用户还有其他的相关内容都会被抓出来发给手机端
String jpql = "select admin from Admin admin where lower(admin.username) = lower(:username)";
考虑到和手机端的交互用JSON当然内容越少越好,提供二种解决办法:
1. 使用Tuple, 并将结果放入自己定义的AdminWrapper
public List<AdminWrapper> getAdminListByTuple() {
//1:
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
//2: One of the JPA ways for getting only particular columns is to ask for a Tuple object.
CriteriaQuery<Tuple> criteriaQuery = criteriaBuilder.createTupleQuery();
//3:
Root<Admin> root = criteriaQuery.from(Admin.class);
//4:
criteriaQuery.multiselect( root.get("id"), root.get("username"), root.get("name") );
//5:条件
Predicate restrictions = criteriaBuilder.conjunction();
restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("id"), 1));
criteriaQuery.where(restrictions);
criteriaQuery.orderBy(criteriaBuilder.desc(root.get("id")));
//5:
TypedQuery<Tuple> query = entityManager.createQuery(criteriaQuery).setFlushMode(FlushModeType.COMMIT);
//6
List<Tuple> tuples = query.getResultList();
AdminWrapper adminWrapper = null;
List<AdminWrapper> lists = new ArrayList<AdminWrapper>();
for (Tuple t : tuples) {
adminWrapper = new AdminWrapper();
adminWrapper.setId((Long)t.get(0));
adminWrapper.setUsername((String)t.get(1));
adminWrapper.setName((String)t.get(2));
lists.add(adminWrapper);
}
return lists;
}
2. 直接使用AdminWrapper,前提是有构造方法
public AdminWrapper() {
}
public AdminWrapper (Long id, String username, String name) {
this.id = id;
this.username = username;
this.name = name;
}
然后
public List<AdminWrapper> getAdminListByT() {
//1:
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
//2: One of the JPA ways for getting only particular columns is to ask for a Tuple object.
CriteriaQuery<AdminWrapper> criteriaQuery = criteriaBuilder.createQuery(AdminWrapper.class);
//3
Root<Admin> root = criteriaQuery.from(Admin.class);
//4
criteriaQuery.multiselect( root.get("id"), root.get("username"), root.get("name") );
//5
TypedQuery<AdminWrapper> query = entityManager.createQuery(criteriaQuery).setFlushMode(FlushModeType.COMMIT);
List<AdminWrapper> lists = query.getResultList();
return lists;
}