DAO 方法检索单个条目
我如何编写 DAO 方法,该方法将仅返回数据库中的第一个条目作为结果。例如,假设我正在查看用户表,我只想检索第一个条目,我将声明如下方法:
public User getFirstUser(){
//method logic
}
编辑:
用户具有主键id如果这很重要。
如果这个问题太简单/愚蠢/不管怎样,我很抱歉我是 Java 初学者,所以我正在尝试新事物。谢谢
我的尝试:
public User getFirstUser(){
try {
final String getQuery = "SELECT * FROM Users WHERE Id = (SELECT MIN(Id) FROM Users)";
final Query query = getSession().createQuery(getQuery);
final int rowCount = query.executeUpdate(); // check that the rowCount is 1
log.debug("get successful");
// return what??
} catch (RuntimeException re) {
log.error("get not successful", re);
throw re;
}
}
How can I write DAO method which will return as a result only first entry from the database. For instance lets say I'm looking at Users table and I want to retrieve only the first entry, I'd declare method like:
public User getFirstUser(){
//method logic
}
EDIT:
User has primary key id if that matters at all.
I apologize if this question is too simple/stupid/whatever I'm beginner with Java so I'm trying new things. thank you
My attempt :
public User getFirstUser(){
try {
final String getQuery = "SELECT * FROM Users WHERE Id = (SELECT MIN(Id) FROM Users)";
final Query query = getSession().createQuery(getQuery);
final int rowCount = query.executeUpdate(); // check that the rowCount is 1
log.debug("get successful");
// return what??
} catch (RuntimeException re) {
log.error("get not successful", re);
throw re;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
SELECT * FROM Users WHERE Id = (SELECT MIN(Id) FROM Users)
:)
SELECT * FROM Users WHERE Id = (SELECT MIN(Id) FROM Users)
:)
不太记得了,但我认为 JPA 和 Hibernate 中有一个 getSingleResult 方法,所以...
但是当返回多个结果时,这个方法可能会抛出异常...不记得了...
实际上也有 getResultList 返回实体列表,你可以做 list.get(0) 不?
或者创建一个带有 LIMIT 1 的查询?
Don't remember exactly but i think there is a method getSingleResult in JPA and also in Hibernate so...
But this method perhaps throw exception when multiple results are returned... can't remember...
Actually there is also getResultList returning a List of entities, and you could do list.get(0) no?
Or create a query with LIMIT 1?
在 MS SQL Server 中,我们这样做,
第一个用户,最小 ID,
最新用户,最大 ID,
谢谢。
In MS SQL Server we do it like,
First user, min ID,
Latest user, max ID,
thanks.
您可以
使用:
使用
User user = session.get(User.class, id);
如果你预先知道ID。You can
use:
use
User user = session.get(User.class, id);
if you know the ID upfront.获取按 id 排序的所有用户并将结果限制为 1(但不要使用
LIMIT
,使用setMaxResults()
保持可移植性):Get all users ordered by id and limit the results to 1 (but don't use
LIMIT
, usesetMaxResults()
to remain portable):