如何在 Hibernate Native SQL 查询中急切获取连接表集合?

发布于 2024-11-09 01:13:51 字数 1228 浏览 0 评论 0原文

我有以下三个数据库表

  1. Customer
  2. Product
  3. CustomerProductRelation

与这些表对应,我有两个 Hibernate POJO 的

  1. Product
  2. 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.(DefaultEntityAliases.java:37) at org.hibernate.loader.ColumnEntityAliases.(ColumnEntityAliases. java:16) at org.hibernate.loader.custom.sql.SQLQueryReturnProcessor.generateCustomReturns(SQ‌ LQueryReturnProcessor.java:264)

如果有人知道这个问题的解决方案,请告诉我。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

合约呢 2024-11-16 01:13:51

这是您所看到的吗? (HHH-2225)

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文