[英]Hibernate: getting data from two linked tables using Ctriteria API
如何使用Ctriteria API通過值“ ispasssed ”(布爾值)從兩個鏈接表(一對多:一個用戶和多個結果)中獲取數據?
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
你可以使用HQL:
from usertable u, resulttable r where u.id = r.id
where r.ispassed = 1
這將返回[User,result]數組的列表。
改變你的代碼如:
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();
您可以像下面一樣創建實體類
@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方法獲取所有結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.