Hibernate JPA 如何使用SQL文直接查询

对于复杂SQL,可以直接调用native sql来是实现

 public List<Partner> findPartners() {
        List<Partner> partnerList = new ArrayList<>();
// 这里的em是注入的EntityManager List
<Object> partners = this.em.createNativeQuery("select id, no, name from partner").getResultList(); for(Object obj : partners){ Object[] objArray = this.convertToObjectArray(obj); Partner partner = new Partner(); partner.setId(objArray[0].toString()); partner.setNo(objArray[1].toString()); partner.setName(objArray[2].toString()); partnerList.add(partner); } return partnerList; } // 将Object转化为数组 private Object[] convertToObjectArray(Object array) { Class ofArray = array.getClass().getComponentType(); if (ofArray.isPrimitive()) { List ar = new ArrayList(); int length = Array.getLength(array); for (int i = 0; i < length; i++) { ar.add(Array.get(array, i)); } return ar.toArray(); } else { return (Object[]) array; } }

 

posted @ 2017-03-06 15:31  栖息之鹰  阅读(275)  评论(0编辑  收藏  举报