public abstract class BaseServiceImpl implements BaseService { @Autowired protected BaseRepository baseRepository; @PersistenceContext(unitName="primaryPersistenceUnit") @Qualifier(value = "primaryDataSource") @Autowired protected EntityManager entityManager; @Override public List findAllByNavtiveSQLBase(String sql){ try { Query query = entityManager.createNativeQuery(sql); @SuppressWarnings("unchecked") List list = query.getResultList(); System.out.println("list.size() = " + list.size()); entityManager.close(); return list; } catch (RuntimeException ex) { throw ex; } } @Override public Page findAllByNavtiveSQLPagingBase(String sql, Pageable pageable){ try { Query query = entityManager.createNativeQuery(sql); long total = query.getResultList().size(); Iterator orders = pageable.getSort().iterator(); String pageOrder = orders.hasNext() ? "order by" : ""; while (orders.hasNext()) { Order order = (Order) orders.next(); pageOrder += String.format(" %s %s%s", order.getProperty(), order.getDirection(), (orders.hasNext() ? ", " : "")); } int size = pageable.getPageSize(); int begin = (pageable.getPageNumber() - 1) * size; String pageSql = String.format("%s %s limit %s, %s", sql, pageOrder, begin, size); System.out.println("pageSql = " + pageSql); query = entityManager.createNativeQuery(pageSql); @SuppressWarnings("unchecked") List list = query.getResultList(); entityManager.close(); return new PageImpl (list, pageable, total); } catch (RuntimeException ex) { throw ex; } }}
@Servicepublic class ServiceAttendanceRecordImpl extends BaseServiceImpl implements ServiceAttendanceRecord {}
所有继承了BaseServiceImpl类的实现默认都有了通用的sql查询功能
如何使用
List list = serviceCompanyEntityImpl.findAllByNavtiveSQLBase("SELECT A, B, C FROM T"); for (Object[] objects : list) { for (Object object : objects) { } }