我正在开发Hibernate
,其中我有两个表,例如Country
和City
国家/地区:
Id int(20) NOT NULL,
CountryName int(30) NOT NULL,
主键(Id)
城市:
CId int(20) NOT NULL,
城市名称 varchar(30) NOT NULL,
状态 varchar(30) NOT NULL,
添加约束
cid外键(
国家)引用
id(
Id);
- 表示
城市
与国家
映射的多对一
现在我需要从Country
访问City
详细信息
- 我已经创建了“Country.hbm.xml”
- 我已经创建了“City.hbm.xml”
查询:
从 Country 中选择 a.countryName、a.cities.cityName、a.cities.state 作为
查询结果
org.hibernate.QueryException:非法尝试使用元素属性引用 [cityName][select a.countryName,a.cities.cityName,a.cities.state from Country] 取消引用集合 [country0_.Id.cities]作为]
我不知道为什么它会显示这个异常...,如果有人知道,这对我来说将是一个很大的荣幸..!!
注意:我正在从 parent 那里检索 child 的详细信息
最佳答案
在您的 Country 实体中为 City 定义一个 @OneToMany 映射,如下所示。即一个国家可以有许多城市。
@OneToMany(targetEntity = City.class, cascade = { CascadeType.ALL })
private List<City> cites;
然后,一旦您加载了国家/地区,只需调用country.getCities(),它将返回该国家/地区的所有城市。
关于java - 如何在 hibernate 中从父表检索子表记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22831895/