My Title

Java JPA 查询实体部分字段

前言

相信大家在用Java JPA作为ORM的时候都会有这种困惑,就是某个表T我仅仅希望取到其中的A、B、C三个字段,可是jpa是通过Entity Class映射的方式组合查询结果的。
那么如何通过使用JPA查询部分想要的内容,下面我把它做了一些通用的封装,供大家参考。痛快点,直接上代码!

实现


public interface BaseService<T,ID extends Serializable>  {
	
	List<Object[]> findAllByNavtiveSQLBase(String sql);
	
	Page<Object[]> findAllByNavtiveSQLPagingBase(String sql, Pageable pageable);
}


public abstract class BaseServiceImpl<T, ID extends Serializable> implements BaseService<T, ID>   {

    @Autowired
    protected BaseRepository<T, ID> baseRepository;
    @PersistenceContext(unitName="primaryPersistenceUnit")
    @Qualifier(value = "primaryDataSource")
    @Autowired
    protected EntityManager entityManager;

	@Override
	public List<Object[]> findAllByNavtiveSQLBase(String sql){
		try {
			Query query = entityManager.createNativeQuery(sql);
			@SuppressWarnings("unchecked")
			List<Object[]> list = query.getResultList();
			System.out.println("list.size() = " + list.size());
			entityManager.close();
			return list;
		} catch (RuntimeException ex) {
			throw ex;
		}
	}
	
	@Override
	public Page<Object[]> findAllByNavtiveSQLPagingBase(String sql, Pageable pageable){
		try {
			Query query = entityManager.createNativeQuery(sql);
			long total = query.getResultList().size();

			Iterator<Order> 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<Object[]> list = query.getResultList();

			entityManager.close();
			return new PageImpl<Object[]>(list, pageable, total);
		} catch (RuntimeException ex) {
			throw ex;
		}
	}
}



@Service
public class ServiceAttendanceRecordImpl extends BaseServiceImpl<AttendanceRecord,Integer> implements ServiceAttendanceRecord {

}

所有继承了BaseServiceImpl类的实现默认都有了通用的sql查询功能

如何使用


List<Object[]> list = serviceCompanyEntityImpl.findAllByNavtiveSQLBase("SELECT A, B, C FROM T");
		for (Object[] objects : list) {
			for (Object object : objects) {

			}
		}

posted @ 2016-10-10 17:01  Jared.Nie  阅读(1474)  评论(0编辑  收藏  举报
IP查询