Hibernate:使用Ctriteria API从两个链接表中获取数据

时间:2015-04-23 06:19:36

标签: java hibernate criteria-api

如何通过值' 绕过'从两个链接表(一对多:一个用户和多个结果)中获取数据? (布尔)使用Ctriteria API? enter image description here

    private List<?> winners;    

    try {           
            SessionFactory factory = HibernateUtil.getSessionFactory();
            Session hSession = factory.openSession();
            Transaction tx = null;

                try {

                    tx = hSession.beginTransaction();
                    winners = hSession.createSQLQuery("select * from usertable u, resulttable r where u.id = r.id where r.ispassed = true").list();
                    tx.commit();

                } catch (Exception e) {
                    if (tx != null)
                        tx.rollback();
                } finally {
                    hSession.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            System.out.println(winners.size()); // an exception

2 个答案:

答案 0 :(得分:2)

您可以使用HQL:

from usertable u, resulttable r where u.id = r.id
where r.ispassed = 1

这将返回[用户,结果]数组的列表。

将代码更改为:

private List<?> winners;    

try {           
    SessionFactory factory = HibernateUtil.getSessionFactory();
    Session hSession = factory.openSession();
    Transaction tx = null;

        try {

            tx = hSession.beginTransaction();
            winners = hSession.createSQLQuery("from usertable u, resulttable r where u.id = r.id and r.ispassed = true").list();
            tx.commit();

        } catch (Exception e) {
            if (tx != null)
                tx.rollback();
        } finally {
            hSession.close();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    System.out.println(winners.size());

修改

CriteriaBuilder b = em.getCriteriaBuilder();
CriteriaQuery<Tuple> c = b.createTupleQuery();
Root<EntityX> entityXRoot= c.from(EntityX.class);
Root<EntityY> entityYRoot = c.from(EntityY.class);

List<Predicate> predicates = new ArrayList<>();
//Here you need to add the predicates you need

List<Predicate> andPredicates = new ArrayList<>();
andPredicates.add(b.equal(entityXRoot.get("id"), entityYRoot.get("id")));
andPredicates.add(b.and(predicates.toArray(new Predicate[0])));

c.multiselect(entityXRoot, entityYRoot);
c.where(andPredicates.toArray(new Predicate[0]));

TypedQuery<Tuple> q = em.createQuery(criteria);

List<Tuple> result = q.getResultList();

答案 1 :(得分:1)

您可以像下面那样创建您的实体类

@Entity
@Table(name="RESULTS")
public class Results implements Serializable {
    @Id
    @GeneratedValue()
    @Column(name="ID")
    private Long id;

    @ManyToOne
    @JoinColumn(name="USER_ID")
    private User userId;

    @Column(name = "IS_PASSED")
    private Boolean ispassed;

    other property
    ... getter() setter()
}

@Entity
@Table(name="USER")
public class User implements Serializable {
    @Id
    @GeneratedValue()
    @Column(name="ID")
    private Long id;

    @OneToMany(mappedBy = "userId",cascade=CascadeType.ALL)
    private Set<Results> resultsSet;

    other property
    ... getter() setter()
}

在你的hibernate.cfg.xml文件中,如果设置在属性

下面
<property name="hibernate.query.substitutions">true 1, false 0</property>

执行以下HQL查询

String sql = "from User as user "
                + "inner join user.resultsSet"
                + "where resultsSet.ispassed= true";
        Query query = getCurrentSession().createQuery(sql);
        List<User> UserList = query.list();

以上是如何获取用户列表,现在需要迭代用户列表并使用getter方法获取所有结果。