0

I'm writing an application that use Hibernate to query the database (SQL Server). Now I'm querying a link table for all Items.

The query looks like:

"FROM UserRole ur join ur.platformUser join ur.role join ur.company"

I need all the UserRoles objects in a list but when I query the above query I got a arrao of objects with UserRole, Role, Company and PlatformUser objects in it.

enter image description here

I only need the UserRole objects with the other objects in the UserRole object. How can I solve this in Hiernate that I can cast the result to for ex. Arraylist<UserRole>?

I tried following syntax:

Query query = session.createSQLQuery("select * FROM UserRole ur join PlatformUser pu ON pu.userId = ur.userId join [Role] r ON r.roleId = ur.roleId join [Company] c ON c.companyId = ur.companyId").addEntity(UserRole.class);

With this line I got a List of UserRoles but all the underlying objects are NULL.

1 Answer 1

1

It could be that you've mapped the fields in the UserRole as lazy loaded? (Or haven't specified, I believe lazy loading is the default)

Try writing something along the lines of

Object obj = userRoles.get(0).getName(); //Or any of the previously null valued fields you have in there

Make sure you're writing this still within session, preferably right after the query.list(); itself

That should lazy load the value, and if that was indeed the case, look into initializing hibernate objects.

edit: If you're looking for a more proper way of doing this, there's actually a hibernate method that requests to initialize a proxy object, I'm unsure why it's better than just getting the thing you want to initialize from code, but it sure is prettier.

Hibernate.initialize(Object initializeMe)

But as far as I know, it's a shallow method, meaning it won't load entities inside of this one. To achieve that you'll need to either do it by hand, or make a generic method that'll load everything, think reflection & recursive.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.