java.lang.ClassCastException:[Ljava.lang.Object;不能转发给iland.hbm.BillDetails`

时间:2014-07-11 10:04:38

标签: java hibernate hql

以下是我的代码,我从多个表中获取数据并想要打印该数据。

对于获取数据,我使用以下方法

 public List<BillDetails> fetch(long id, long cid) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        List<BillDetails> obj = null;
        try {
            String hql = "select distinct bd,sum(bpds.amount) from BillDetails as bd "
                    + "left join fetch bd.customerDetails as cd "
                    + "left join fetch bd.billProductSet as bpd "
                    + "left join fetch bpd.product as pd "
                    + "left join fetch bd.billPaidDetails as bpds "
                    + "where bd.billNo=:id "
                    + "and bd.client.id=:cid ";

            Query query = session.createQuery(hql);
            query.setParameter("id", id);
            query.setParameter("cid", cid);
            obj = query.list();
            tx.commit();

        } catch (HibernateException e) {
            if (tx != null) {
                e.printStackTrace();
                tx.rollback();
            }
        } finally {
            session.close();
        }
        System.out.println("Size is " + obj.size());
        System.out.println("  " + obj.get(0).getBillNo());
        return obj;
    }

BillDetails pojo

public class BillDetails implements java.io.Serializable {
 private Long billNo;
    private CustomerDetails customerDetails;
    private Client client;
    private BigDecimal subTotal;
    private BigDecimal vat;
    private BigDecimal total;
    private String invoiceNo;
    private Date invoiceDate;
    private String status;
    private Timestamp addDate;
    private Set<BillPaidDetails> billPaidDetails = new HashSet(0);
     private Set<BillProduct> billProductSet = new HashSet(0);
    //getter and setter
   }

BillPaidDetails

public class BillPaidDetails implements java.io.Serializable {

    private Long id;
    private Client client;
    private BillDetails billDetails;
    private BigDecimal amount;
    private String paymentMode;
    private Date dt;
    private Timestamp adddate;
}

fetch() System.out.println(" " + obj.get(0).getBillNo());打印价值 它正在显示 Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to iland.hbm.BillDetails

如何解决上述异常以及sum(bpds.amount)将存储的位置。 sum(bpds.amount)是否可以存储在BillPaidDetails的任何所需字段中,例如添加了将存储和的字段private BigDecimal totalAmount;

1 个答案:

答案 0 :(得分:0)

首先,这个查询无法正常工作。 I already responded关于是否需要包含所有获取的实体&#39; group by子句中的属性。

您尝试同时选择实体和总和,同时期望适合List<BillDetails>

如果您只选择BillDetails,那就没事了。但是,当您想要选择多个实体时,需要将选择分配给List<Object[]>

List<Object[]> obj = null;
...
Object[] bdAndSum = obj.get(0);
BillDetails bd = (BillDetails) bdAndSum.get(0);
Number sum = (Number) bdAndSum.get(1);