【问题标题】:Spring Hibernate access joined database fieldSpring Hibernate 访问加入的数据库字段
【发布时间】:2011-09-23 20:16:36
【问题描述】:

我的数据库表:

cities(id serial, name varchar(40);
weather(id serial, city_id int, temp int, date date)

cities.id = weather.city_id

在 Spring 中,我拥有与数据库中的字段相同的 POJO。

例如 City.java:

@Entity
@Table(name="CITIES")
public class City {

    @Id
    @Column(name="ID")
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "CITIES_ID_SEQ")
    @SequenceGenerator(name = "CITIES_ID_SEQ", sequenceName="cities_id_seq", allocationSize=1)
    private Integer id;

    @Column(name="NAME")
    private String name;
        //here come getters and setters

DAO - 所以这将返回给控制器,控制器将其发送到 JSP:

public Weather getWeatherById(Integer id) {
    return (Weather) sessionFactory.getCurrentSession().get(Weather.class, id);
}

控制器:

model.addAttribute("weather", weatherService.getWeatherById(id));

问题是,如何从 JSP 访问cities.name?或者,如果没有特殊查询,这是不可能的?

【问题讨论】:

  • 城市是天气抽象的一部分吗?如果是,您可以从那里访问它和它的名称。
  • @mkro : 你在抽象下是什么意思?
  • 正如@danny.lesnik 的回答所暗示的那样:您需要一个天气信息类,并且该类应该连接到城市。

标签: hibernate spring jsp spring-mvc


【解决方案1】:

这两个对象应该具有双向的一对一关系。

public class City{

@One-To-One
private Weather weather;

}

第二类:

public class Weather {

@One-to-One
private City city;

}

然后您可以使用 getWeather() 获取城市并获取其天气,或者您可以获取天气并获取其城市。

或者,您可以使用 HQL 连接语句来获取城市:

from City c join c.weather wheather where wheather.id = :id .

【讨论】:

  • 我必须更改数据库中的任何内容吗?或者city_id 可能会保留为int?或者我必须在数据库中创建某种关系?目前我只有这两张表,只有我知道cities.id = weather.city_id
  • 实际上 Hibernate 可以为您完成所有必需的工作,您只需要创建正确的关系:我只是建议您阅读有关一对一关系的文章,它可能会为您提供清晰的图片:@987654321 @
【解决方案2】:

实际上,这对我来说似乎不是一对一的关系,而是多对一的关系。尝试为孩子们使用以下内容:

public class Weather {

@Many-to-One
private City city;

}

对于父母:

public class City{

@One-To-Many
private Weather weather;

}

【讨论】:

    猜你喜欢
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-02
    • 1970-01-01
    • 2016-12-13
    相关资源
    最近更新 更多