SpringData JPA框架使用时多表关联返回自定义参数方案

关联多张表构造方法返回自定义字段写法

/*
*构造方法类
*放入Constant类中作为常量配置,便于管理
*
/
JpaVoConstants.XXVO = " new com.XX.XX.XXVO " 
//受到容器托管的EntityManager可以直接通过注解@PersistenceContext注入的方式来获得
@PersistenceContext
 private EntityManager entityManager;
 
//Java EE环境获得EntityManagerFactory
@PersistenceUnit(unitName="jpa-1")
private EntityManagerFactory emf;

//Java SE环境获得EntityManagerFactory
EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa-1");

//From Address:https://www.jianshu.com/p/091360c47e6b
 /*
 *【测试用】
 *请先熟悉HQL语句写法
 *接收多个参数(推荐使用对象封装参数)
 *自定义返回想要查询参数
 * 
 /
@Override
    public Page findAll(Pageable pageable, String... properties) {
        String sql = "select  " + JpaVoConstants.XXVO +"";
        sql += "   where 1=1  ";
        sql += !properties[0].equals("") ? " and A = :A  " : "";
        sql += !properties[1].equals("") ? " and B = :B  " : "";
        sql += !properties[2].equals("") ? " and C = :C  " : "";
        sql += "   order by  bps.id ";
        Query query = entityManager.createQuery(sql);
        if (!properties[0].equals("")) {
            query.setParameter("A", properties[0]);
        }
        if (!properties[1].equals("")) {
            query.setParameter("B", properties[1]);
        }
        if (!properties[2].equals("")) {
            query.setParameter("C", properties[2]);
        }
        query.setFirstResult(pageable.getOffset());
        query.setMaxResults(pageable.getOffset() + pageable.getPageSize());
        List list = query.getResultList();
        long total = list .size();
        Page voPage = new PageImpl(list, pageable, total);
        return voPage;
    }

你可能感兴趣的:(JPA,Java,Why)