user767494
user767494

Reputation: 31

How to eager fetch join table collection in Hibernate Native SQL Query?

I have following three database tables

  1. Customer
  2. Product
  3. CustomerProductRelation

Corresponding to these tables, I have two Hibernate POJO's

  1. Product
  2. Customer

One of the member variable is a joinTable:

@JoinTable(name = "CustomerProductRelation", joinColumns = { @JoinColumn(name = "CUSTOMER_ID") }, inverseJoinColumns = { @JoinColumn(name = "PRODUCT_ID") })
private List<Product> products;

Due to some reason, I need to use a native SQL query on Customer table, in that case how do I eager fetch products in my customer list?

I am doing something similar to this:

String queryString = "select c.*,cpr.product_id from Customer c, CustomerProductRelation cpr where c.customer_id = cpr.customer_id";
List list = getSession().createSQLQuery(queryString)
                .addEntity("c", Customer.class)
                .addJoin("p", "c.products").list();

This does not seem to work. The exception is as follows:

java.lang.NullPointerException at org.hibernate.loader.DefaultEntityAliases.<init>(DefaultEntityAliases.java:37) at org.hibernate.loader.ColumnEntityAliases.<init>(ColumnEntityAliases.java:16) at org.hibernate.loader.custom.sql.SQLQueryReturnProcessor.generateCustomReturns(SQ‌​LQueryReturnProcessor.java:264)

Please let me know if anyone knows the solution to this.

Upvotes: 3

Views: 5954

Answers (1)

Alex Barnes
Alex Barnes

Reputation: 7218

Is this what you are seeing? (HHH-2225)

Upvotes: 1

Related Questions