Spring Hibernate访问加入数据库字段

时间:2011-09-23 20:16:37

标签: hibernate spring jsp spring-mvc

我的数据库表:

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?或者这是不可能的,没有特殊查询?

2 个答案:

答案 0 :(得分:2)

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

public class City{

@One-To-One
private Weather weather;

}

和第二节课:

public class Weather {

@One-to-One
private City city;

}

然后你可以使用getWeather()获取城市并获取天气,或者你可以获取天气并获得它的城市。

或者,您可以使用HQL join语句来获取city:

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

答案 1 :(得分:0)

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

public class Weather {

@Many-to-One
private City city;

}

和父母:

public class City{

@One-To-Many
private Weather weather;

}