![](/img/trans.png)
[英]Hibernate Criteria to query more than one class (or restrict by a list of subclasses)
[英]Hibernate Criteria for tables with more than one relationsship
我有一個包含兩個表(城市,國家/地區)以及它們之間的兩個關系的數據庫。
第一個是“一個國家有多個城市”的關系。
select * from City inner join Country on(code=countrycode);
第二個是“一個國家有一個資本”的關系。
select * from City inner join Country on(capital=id);
休眠條件對於第一個關系很好用,例如
Criteria criteria = session.createCriteria(City.class);
List<City> = criteria
.createCriteria("countrycode")
.add(Restrictions.eq("continent", continent))
.list();
但是,如何創建休眠條件來檢索大寫字母列表? 第二個關系是未映射的。 Hibernate是否支持這種關系?
市級:
@Entity
public class City {
@Id
@Column(name = "ID", updatable = false, nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
...
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "countrycode", nullable = false)
private Country countrycode;
...
國家類別:
@Entity
public class Country {
@Id
private String code;
@OneToMany(targetEntity = City.class, mappedBy = "countrycode")
private Set<City> cities;
private Integer capital;
...
城市是否為任何國家的首都的信息必須在城市之內。 向City添加一個布爾字段,如下所示:
List<City> = session.createCriteria(City.class)
.createCriteria("countrycode")
.add(Restrictions.eq("continent", continent))
.add(Restrictions.eq("capital", true))
.list();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.