开发者

Spring Hibernate access joined database field

开发者 https://www.devze.com 2023-04-08 14:08 出处:网络
my database tables: cities(id serial, name varchar(40); weather(id serial, city_id int, temp int, date date)

my database tables:

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

cities.id = weath开发者_开发知识库er.city_id

In Spring I have same POJO as the fields in database.

for example 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 - so this will be returned to controller, which sends it to JSP:

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

Controller:

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

Question is that, how can I access the cities.name from JSP? Or that is not possible, without special query?


These two objects should have biderectional one-to-one releationship.

public class City{

@One-To-One
private Weather weather;

}

and the second class:

public class Weather {

@One-to-One
private City city;

}

then you can fetch city and get its weather using getWeather() or you can fetch weather and get its city.

Alternatively, you can use HQL join statement to fetch city:

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


Actualy, this does not seem like a one-to-one relationship to me but rather a many-to-one. Try using the following for the children:

public class Weather {

@Many-to-One
private City city;

}

and for the parent:

public class City{

@One-To-Many
private Weather weather;

}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号