【问题标题】:How to retrieve child table records from parent in hibernate?如何在休眠中从父级检索子表记录?
【发布时间】:2023-03-15 22:04:01
【问题描述】:

我正在处理Hibernate,我有两张表,例如Country 和City

国家:

Id int(20) NOT NULL, CountryName int(30) NOT NULL, PRIMARY KEY (Id)

城市:

CId int(20) NOT NULL, CityName varchar(30) NOT NULL, State varchar(30) NOT NULL, ADD CONSTRAINTcidFOREIGN KEY (Country) REFERENCESid(Id);

  • 表示City 与Country 映射的多对一

现在我需要从Country 访问City 详细信息

  • 我已经创建了“Country.hbm.xml”
  • 我已经创建了“City.hbm.xml”

查询:

select a.countryName,a.cities.cityName,a.cities.state from Country as a

查询结果

org.hibernate.QueryException: illegal attempt to dereference colection[country0_.Id.cities] with element property reference[cityName][select a.countryName,a.cities.cityName,a.cities.state from Country as a]

我不知道为什么它会显示这个异常...,如果有人知道,我会很高兴..!!

注意:我正在从父母那里检索孩子的详细信息

【问题讨论】:

    标签: java mysql hibernate exception


    【解决方案1】:

    在您的 Country 实体中,像这样为 City 定义一个 @OneToMany 映射。即一个国家可以有许多城市。

    @OneToMany(targetEntity = City.class, cascade = { CascadeType.ALL })
    private List<City> cites;
    

    然后,一旦您加载国家/地区,只需调用 country.getCities() 即可返回该国家/地区的所有城市。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-17
      • 1970-01-01
      • 2016-11-17
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      相关资源
      最近更新 更多