java - Hibernate: getting data from two linked tables using Ctriteria API -
how can data 2 linked tables (one-to-many: 1 user , many results) value 'ispassed' (boolean) using ctriteria api?
private list<?> winners; try { sessionfactory factory = hibernateutil.getsessionfactory(); session hsession = factory.opensession(); transaction tx = null; try { tx = hsession.begintransaction(); winners = hsession.createsqlquery("select * usertable u, resulttable r u.id = r.id r.ispassed = true").list(); tx.commit(); } catch (exception e) { if (tx != null) tx.rollback(); } { hsession.close(); } } catch (exception e) { e.printstacktrace(); } system.out.println(winners.size()); // exception
you can use hql:
from usertable u, resulttable r u.id = r.id r.ispassed = 1
this return list of [user,result] arrays.
change code like:
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 u.id = r.id , r.ispassed = true").list(); tx.commit(); } catch (exception e) { if (tx != null) tx.rollback(); } { hsession.close(); } } catch (exception e) { e.printstacktrace(); } system.out.println(winners.size());
edit:
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 need add predicates 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();