I've got a database with two tables (City, Country) and two relations between them.
The first one is the "a country has multiple cities" relation.
select * from City inner join Country on(code=countrycode);
The second one is the "a country has one capital" relation.
select * from City inner join Country on(capital=id);
Hibernate criterias work fine for the first relation, e.g.
Criteria criteria = session.createCriteria(City.class);
List<City> = criteria
.createCriteria("countrycode")
.add(Restrictions.eq("continent", continent))
.list();
But how can I create an Hibernate criteria to retrieve a list of capitals? The second relation is unmapped. Does Hibernate support this kind of relationship?
The City class:
@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;
...
The Country class:
@Entity
public class Country {
@Id
private String code;
@OneToMany(targetEntity = City.class, mappedBy = "countrycode")
private Set<City> cities;
private Integer capital;
...
The information whether or not the city is capital of any country has to be within City. Add a boolean field to City an query it like that:
List<City> = session.createCriteria(City.class)
.createCriteria("countrycode")
.add(Restrictions.eq("continent", continent))
.add(Restrictions.eq("capital", true))
.list();