1

I have Hibernate generated classes that contain other classes -

public class BookLoans implements java.io.Serializable { private BookLoansId id; private Borrower borrower; private LibraryBranch libraryBranch; private Book book; private Date dateOut; private Date dueDate; } 

where BookLoansId is -

public class BookLoansId implements java.io.Serializable { private int bookId; private int branchId; private int cardNo; } 

which are primary keys in the tables Book, LibraryBranch and Borrower respectively. When I run this query -

sessionFactory.getCurrentSession().createSQLQuery( "select * from library.tbl_book_loans l where cardNo = 4"); 

Hibernate returns a list of Object[] elements. If I try to iterate through this list, I get null objects. I've tried a couple of different methods from here and here.

Is there any way to find out how the objects are arranged within each Object[]?

2 Answers 2

1

To directly map the query result to an entity objct use addEntity(BookLoans.class);

 sessionFactory.getCurrentSession().createSQLQuery( "select * from library.tbl_book_loans l where cardNo = 4") .addEntity(BookLoans.class); 

See the docs(16.1.2. Entity queries): http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querysql.html

However the result of nulls you get from your attempt is strange. Hibernate should give you List of Objects arrays where each Object array represents the fields in one row of the result set. Check if the query actualy returns something.

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

3 Comments

I get a null pointer exception if I try to access the mapped objects. And just nulls if I try to print out the date fields. However, object[].tostring() prints a hashcode on the the console. Is there a way to tell what order the fields are in the array? Are they arranged in the same order as the Class's attributes?
Probably the order is the same as in the table(not sure). What data is in the table? Can you execute the same query from some sql tool and show us the result?
The table simply has three int columns - bookId, branchId, cardNo and 2 date fields - dateOut, dueDate. The SQL query runs correctly when I run it on MySQL Workbench. Going to give it another shot and update with results.
0

I solved this by using HQL:

from library.tbl_book_loans where borrower.cardNo = 4 

Hibernate now correctly populates all mapped entities.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.