简体   繁体   English

DAO方法检索单个条目

[英]DAO method retrieve single entry

How can I write DAO method which will return as a result only first entry from the database. 我如何编写DAO方法,该方法将仅从数据库中的第一个条目返回结果。 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. 用户有主键ID(如果有的话)。

I apologize if this question is too simple/stupid/whatever I'm beginner with Java so I'm trying new things. 如果这个问题太简单/愚蠢/无论我是Java的初学者,我都表示歉意,因此我正在尝试新事物。 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; 
            } 
    }

You can 您可以

  • use: 采用:

     Query query = session.createQuery("from User"); query.setMaxResults(1); User result = (User) query.uniqueResult(); 
  • use User user = session.get(User.class, id); 使用User user = session.get(User.class, id); if you know the ID upfront. 如果您事先知道ID。

Get all users ordered by id and limit the results to 1 (but don't use LIMIT , use setMaxResults() to remain portable): 按ID将所有用户排序,并将结果限制为1(但不要使用LIMIT ,请使用setMaxResults()保持可移植性):

Query q = session.createQuery("from User u order by u.id");
q.setMaxResults(1);
User u = (User) q.uniqueResult();

SELECT * FROM Users WHERE Id = (SELECT MIN(Id) FROM Users)

:)

Don't remember exactly but i think there is a method getSingleResult in JPA and also in Hibernate so... 完全不记得了,但是我认为JPA和Hibernate中都有一种方法getSingleResult ...

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? 实际上,还有getResultList返回实体列表,您可以执行list.get(0)否?

Or create a query with LIMIT 1? 还是使用LIMIT 1创建查询?

In MS SQL Server we do it like, 在MS SQL Server中,我们这样做,

First user, min ID, 第一个用户,最小ID,

SELECT TOP 1 * FROM Users ORDER BY Id

Latest user, max ID, 最新用户,最大ID,

SELECT TOP 1 * FROM Users ORDER BY Id DESC

thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM