如何在 Hibernate Native SQL 查询中急切获取连接表集合?
我有以下三个数据库表
- Customer
- Product
- CustomerProductRelation
与这些表对应,我有两个 Hibernate POJO 的
- Product
- Customer
其中一个成员变量是 joinTable:
@JoinTable(name = "CustomerProductRelation", joinColumns = { @JoinColumn(name = "CUSTOMER_ID") }, inverseJoinColumns = { @JoinColumn(name = "PRODUCT_ID") })
private List<Product> products;
由于某种原因,我需要对 Customer 表使用原生 SQL 查询,在这种情况下如何快速获取客户列表中的产品?
我正在做类似的事情:
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();
这似乎不起作用。异常如下:
java.lang.NullPointerException at org.hibernate.loader.DefaultEntityAliases.
如果有人知道这个问题的解决方案,请告诉我。
I have following three database tables
- Customer
- Product
- CustomerProductRelation
Corresponding to these tables, I have two Hibernate POJO's
- Product
- 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(SQLQueryReturnProcessor.java:264)
Please let me know if anyone knows the solution to this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是您所看到的吗? (HHH-2225)
Is this what you are seeing? (HHH-2225)