Java 使用休眠检索单行单列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24254061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieve single row and single column using hibernate
提问by dimas
I know how to retrieve multiple columns or rows or both using the Hibernate method below. However am not sure how to retrieve only a single row or column and assign it to a String variable. Any help on this? Thanks
我知道如何使用下面的 Hibernate 方法检索多个列或行或两者。但是我不确定如何只检索单行或单列并将其分配给 String 变量。这有什么帮助吗?谢谢
Session session = getSessionFactory().beginSession();
Transaction transaction = null;
StringBuilder sql = new StringBuilder();
sql.append("SELECT DISTINCT B.COLUMN_NAME ");
sql.append("FROM ALL_CONSTRAINTS A, ALL_CONS_COLUMNS B, ARCTBL C ");
sql.append("WHERE A.TABLE_NAME = :TABLE_NAME AND A.CONSTRAINT_TYPE = 'P' ");
sql.append("AND A.CONSTRAINT_NAME = B.CONSTRAINT_NAME ");
sql.append("AND C.TABLENAME=A.TABLE_NAME AND A.TABLE_NAME=B.TABLE_NAME ");
try{
**listOfValues = session.createSQLQuery(sql.toString()).setParameter("TABLE_NAME", table).list();**
//Change this to code below
String returnObjByHibernate = session.createSQLQuery(//Hibernate method)
transaction.commit;
}
catch (Exception e){
//Logic here
采纳答案by inigoD
To get a single row you must use uniqueResult() instead of list()
要获得单行,您必须使用 uniqueResult() 而不是 list()
http://docs.jboss.org/hibernate/orm/3.5/javadocs/org/hibernate/Query.html#uniqueResult()
http://docs.jboss.org/hibernate/orm/3.5/javadocs/org/hibernate/Query.html#uniqueResult()
It returns a String or an array of Strings (I can't remember) so your line should be:
它返回一个字符串或一个字符串数组(我不记得了)所以你的行应该是:
strValue = session.createSQLQuery(sql.toString()).setParameter("TABLE_NAME", table).uniqueResult();
Changing it to uniqueResult()[0] or uniqueResult().get(0) if the returned object is an 'array' or an 'Array'...
如果返回的对象是“数组”或“数组”,则将其更改为 uniqueResult()[0] 或 uniqueResult().get(0)...
回答by anirban
Use uniqueResult()
which returns object. And if there is multiple row matches the sql query then it throws NonUniqueResultException
.
使用uniqueResult()
返回对象。如果有多行匹配 sql 查询,则抛出NonUniqueResultException
.
There is no option for uniqueResult()[0]
or uniqueResult().get(0)
.
uniqueResult()[0]
或没有选项 uniqueResult().get(0)
。
If your query returns multiple query you can use list()
如果您的查询返回多个查询,您可以使用 list()
If you are not sure how many rows are returned by the query but want a single value from one of them. Use list().get(0)
or list()[0]
如果您不确定查询返回了多少行,但想要其中之一的单个值。使用list().get(0)
或list()[0]