Java JPA 查询实体部分字段

前言

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

实现


public interface BaseService  {
    
    List findAllByNavtiveSQLBase(String sql);
    
    Page findAllByNavtiveSQLPagingBase(String sql, Pageable pageable);
}

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;
        }
    }
}


@Service
public 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) {

            }
        }

转载于:https://www.cnblogs.com/Romantic/p/5946403.html

你可能感兴趣的:(Java JPA 查询实体部分字段)