Jaa*_*nus 10 java spring hibernate sessionfactory
这是我的DAO:
public List<Weather> getCurrentWeather() {
return sessionFactory.getCurrentSession().createQuery("from Weather").list();
}
Run Code Online (Sandbox Code Playgroud)
这可以从表天气中获取所有元素.但是,让我说我想做这样的事情(我只希望表天气中的一个元素):
public Weather getCurrentWeather() {
return sessionFactory.getCurrentSession().createQuery("from Weather where id = 1").list(); // here should be something else than list()
}
Run Code Online (Sandbox Code Playgroud)
我知道最终不应该有 list() ,但我必须在那里写什么才能得到一个对象?
Aff*_*ffe 11
如果你有一个id,你只需使用get:
public Weather getCurrentWeather() {
return sessionFactory.getCurrentSession().get(Weather.class, 1);
}
Run Code Online (Sandbox Code Playgroud)
如果您确实需要进行查询,是的,您必须获取结果集的顶部,或者您可以使用uniqueResult()查询.
小智 10
获取列表有什么问题吗?:)即使你知道只有1个休眠也不能假设.无论如何,获取清单更安全!
public Weather getCurrentWeather() {
List<Weather> list = sessionFactory.getCurrentSession().createQuery("from Weather where id = 1").list(); // here should be something else than list()
return (list.isEmpty() ? null : list.get(0));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27729 次 |
| 最近记录: |