相同的数据在hql中多次显示

时间:2014-06-03 05:53:54

标签: hibernate orm hql

我正在使用以下方法从数据库中获取数据。它正在从数据库中正确地获取数据。此处bd.billProductList可以包含一个或多个产品。 问题是,如果只有一个产品,则bd.billProductList大小为1,则obj大小为1。如果bd.billProductList尺寸为5,则obj尺寸为5。 我在jsp页面中迭代它。  如果obj超过1

,则bd.billProductList会多次显示相同的数据
public List<BillDetails> fetch(long id) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        List<BillDetails> obj = null;
        try {
            String hql = "from BillDetails as bd "
                    + "left join fetch bd.customerDetails as cd "
                    + "left join fetch bd.billProductList as bpd "
                    + "left join fetch bpd.productDetails as pd "
                    + "left join fetch pd.sizes "
                    + "left join fetch pd.colors "
                    + "left join fetch pd.productTypes "
                    + "left join fetch pd.productModelDetails "
                    + "where bd.billNo=:id ";


            Query query = session.createQuery(hql);
            query.setParameter("id", id);
            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());
        return obj;
    }

如何解决此问题

1 个答案:

答案 0 :(得分:0)

很简单,你需要DISTINCT:

String hql = "select distinct bd from BillDetails as bd "
                + "left join fetch bd.customerDetails as cd "
                + "left join fetch bd.billProductList as bpd "
                + "left join fetch bpd.productDetails as pd "
                + "left join fetch pd.sizes "
                + "left join fetch pd.colors "
                + "left join fetch pd.productTypes "
                + "left join fetch pd.productModelDetails "
                + "where bd.billNo=:id ";