价值返回方法JPQL的最佳做法

时间:2019-06-26 17:44:28

标签: java jpa persistence jpql

我需要寻求支持,在这段代码中,我最初只需要两个字段, 但我不确定如果只有两个字段或整个对象,如何最好地将查询值返回到下面的方法。

预先感谢

  public LocalDE localizaPorItemstockdeposit(   final BigInteger ItemId, 
                                                  final BigInteger stockId, 
                                                  final BigInteger depositId){

        StringBuilder sql = new StringBuilder();

        sql.append(" SELECT ")
           .append("     c.bkLocationC, ")
           .append("     d.bkStockTypeC ") 
           .append("   FROM LocalDE c ") 
           .append("     JOIN a.partsXWarehouseDE b ")
           .append("     JOIN a.depositDE c  ")
           .append("     JOIN a.TypedepositDE d ")
           .append("   WHERE ")
           .append("      a.ItemId = :ItemId AND")
           .append("      a.stockId = :stockId AND") 
           .append("      a.bkdepositId  = :depositId ");         

        TypedQuery<LocalDE> query = this.entityManager().createQuery(sql.toString(), LocalDE.class);

        query.setParameter("ItemId", ItemId);
        query.setParameter("stockId", stockId);
        query.setParameter("depositId", depositId);

        @SuppressWarnings("unchecked")
        List lstitemxStockxDeposit = query.getResultList();
        java.util.Iterator it = lstitemxStockxDeposit.iterator(); 

        LocalDE itemxStockxDeposit = new LocalDE();
        depositDE deposit = new depositDE();
        TypedepositDE  typeDeposit = new TypedepositDE();

        while(it.hasNext()) {
            Object[] resultitemxStockxDeposit =(Object[]) it.next();

            deposit.setDepositDesc(String.valueOf(resultitemxStockxDeposit[0]));
            typeDeposit.setTypeDepositDEsc(String.valueOf(resultitemxStockxDeposit[1]));

            itemxStockxDeposit.setDepositDE(deposit);
            itemxStockxDeposit.setTypeDepositDE(typeDeposit);
        }

        return itemxStockxDeposit;

    }

1 个答案:

答案 0 :(得分:0)

我曾经这样创建一个DTO:

public class StockxDepositDTO {

        private String deposit;
        private String typeDeposit;

        //with a constructor
        public StockxDepositDTO(String deposit, String typeDeposit){
             this.deposit = deposit;
             this.typeDeposit = typeDeposit;
    }
}

因此,当您获取数据时,可以使用此DTO代替结果集,如下所示:

“从...中选择新的com.stackoverflow.repository.StockxDepositDTO(c.bkLocationC,d.bkStockTypeC)。”

因此,您将收到一个StockxDepositDTO列表,其中包含您需要的两个字段。