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; } }
---栖息之鹰(一个外表懒洋洋的内心有激情的程序员)
此博客为笔者原著,转载时请注明出处,谢谢!