我有这种简单的关系 - 如图所示:
当我尝试阅读某个具有某个Country_id
的城市时,
Country austria = (Country) session.load(Country.class, 1L);
// Works as expected
System.out.println(austria.toString());
Criteria crCities = session.createCriteria(City.class);
crCities.add(Restrictions.eq("Country_id", austria.getId()));
// Crashes ..
List<City> cities = crCities.list();
System.out.println("Show cities of Austria:");
for (City next : cities) {
System.out.println(" - " + next.getName());
}
我收到以下错误:
Exception in thread "main" org.hibernate.QueryException: could not resolve property: Country_id of: com.mahlzeit.datamodel.geographic.City
这是POJO:
Country.java
package com.mahlzeit.datamodel.geographic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table
public class Country {
@Id
@GeneratedValue
private Long id;
private String country_code;
public String getCountryCode() {
return country_code;
}
public void setCountryCode(String countryCode) {
this.country_code = countryCode;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public String toString() {
return "Country [id=" + id.toString() + ", country_code=" + country_code.toString() +"]";
}
}
City.java
package com.mahlzeit.datamodel.geographic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table
public class City {
@Id
@GeneratedValue
private Long id;
@ManyToOne
@JoinColumn(name = "Country_id")
private Country country;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public String toString() {
return "City [id=" + id.toString() + ", country="
+ country.toString() + ", name=" + name + "]";
}
}
我需要做些什么来完成这项工作? City.java 中的@JoinColumn(name = "Country_id")
是否正确?
答案 0 :(得分:2)
您的标准有以下限制:
crCities.add(Restrictions.eq("Country_id", austria.getId()));
这意味着hibernate会搜索名为Country_id
的属性。您的班级City
没有这样的属性。它只有一个名为country
的属性。
所以要么使用对象模型
crCities.add(Restrictions.eq("country", austria));
这是hibernate下的首选方式。
或者,您可以使用更多 SQL ish方式
crCities.add(Restrictions.eq("country.id", austria.getId()));
您明确表示要使用id
的{{1}}属性。
结果和创建的SQL语句应该相同。
答案 1 :(得分:1)
您必须将您的标准更改为crCities.add(Restrictions.eq("country.id", austria.getId()));
。
您无法使用加入列。您必须使用连接对象中的列。