简体   繁体   中英

Hibernate 4 returns list of null object for native sql query

I've recently upgrade from hibernate 3.5 to 4.3.11 with Spring 4.3.9 Before the upgrade everything was working fine. After the upgrade I get this error.

Environment: Java 8, Tomcat 7.0.23, Hibernate 4.3.11, Spring 4.3.9, MSSQL Server 2008,

While executing the following sql query through hibernate, we are getting list of null object with correct size in the list but object are null.

Query:

select DISTINCT(HIERARCHY_ID) from BASETYPE_HIERARCHY_MAPPING 
where BASETYPE_ID IN (select BASETYPE_ID from BASETYPE_GROUP_MAPPING 
where GROUP_ID IN (select GROUP_ID from USER_GROUP_MAPPING where USER_ID like(select ID from USER where USERID='7')))

Java Code:

String sqlQuery="select DISTINCT(HIERARCHY_ID) from BASETYPE_HIERARCHY_MAPPING where BASETYPE_ID IN "
                        + "(select BASETYPE_ID from BASETYPE_GROUP_MAPPING where GROUP_ID IN "
                        + "(select GROUP_ID from USER_GROUP_MAPPING where USER_ID=(select ID from USER where USERID=:userId)))";

Query query = session.createSQLQuery(sqlQuery);
query.setParameter("userId", userId);
List<String> typeId = query.list();

In result list of null objects.I have found similar type of issue for HQL(solution was mistake in mapping) but its simple sql query.

Similar Issue reference link: Hibernate returns list of nulls although executed SQL returns values

You are getting null because you column in not getting mapped here. You can do this step here. Make a class to get HIERARCHY_ID, like this

public class ABC{

    private long id;
}

and then write query like this

@Query("SELECT new com.abc.abc.ABC (t.id) from table t")

This will give you list of ABC object and I think it will work.

Solved the problem using hibernate scalar, by specifying the return type of column in query.

addScalar()

Following changes are done in java code to solve the issue.

String sqlQuery="select DISTINCT(HIERARCHY_ID) from BASETYPE_HIERARCHY_MAPPING where BASETYPE_ID IN "
                        + "(select BASETYPE_ID from BASETYPE_GROUP_MAPPING where GROUP_ID IN "
                        + "(select GROUP_ID from USER_GROUP_MAPPING where USER_ID=(select ID from USER where USERID=:userId)))";

Query query = session.createSQLQuery(sqlQuery).addScalar("HIERARCHY_ID", StringType.INSTANCE);
query.setParameter("userId", userId);
List<String> typeId = query.list();

But in our project lot of sql queries used, so I need to change in all queires any better soluation instead of this addScalar() or why its mandatory from hibernate 4, it was working fine in 3.5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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