我知道如何使用下面的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
最佳答案
要获得单行,必须使用uniqueResult()而不是list()
http://docs.jboss.org/hibernate/orm/3.5/javadocs/org/hibernate/Query.html#uniqueResult()
它返回一个String或一个String数组(我不记得了),因此您的行应为:
strValue = session.createSQLQuery(sql.toString()).setParameter("TABLE_NAME", table).uniqueResult();
如果返回的对象是“数组”或“数组”,则将其更改为uniqueResult()[0]或uniqueResult()。get(0)...