Steve Steve - 2 months ago 3x
Java Question

Hibernate Criteria for tables with more than one relationsship

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
.add(Restrictions.eq("continent", continent))

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:

public class City {

@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:

public class Country {

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)
                .add(Restrictions.eq("continent", continent))
                .add(Restrictions.eq("capital", true))