Hibernate – Formula – 无效查询

huangapple go评论67阅读模式
英文:

Hibernate - Formula - invalid Query

问题

I have a question about Hibernate Formula.

让我们假设我有一个实体"garage",其中有许多"cars"。现在我想在car类中添加一个属性,告诉我它在车库中是第几辆车。

我在car类上创建了这个公式:

@Formula("(SELECT pos FROM (SELECT rownum AS pos, c.id FROM garage g "
+ "LEFT JOIN car c ON g.id = c.garage_id "
+ "WHERE g.id = GARAGE_ID "
+ "ORDER BY c.date) WHERE id = CAR_ID)")

实体car具有两个属性(ID和GARAGE_ID)。如何将它们合并到这个公式中呢?

此外,我遇到了Hibernate总是生成无效的SQL的问题。

Pos变成了query0_.pos。然而,这是无效的。

英文:

I have a question about Hibernate Formula.

Let us assume that I have an entity "garage" in which there are numerous "cars". Now I would like to add a property in the car class that tells me which number of car it is in the garage.

I created this formula on the car-class:

@Formula("(SELECT pos FROM (SELECT rownum AS pos, c.id FROM garage g "
+ "LEFT JOIN car c ON g.id = c.garage_id "
+ "WHERE g.id = GARAGE_ID "
+ "ORDER BY c.date) WHERE id = CAR_ID)")

The entity car has both properties (ID and GARAGE_ID). How can I now incorporate these into the Formula?

Furthermore I have the problem that Hibernate always generates an invalid SQL from it.

Pos becomes query0_.pos. However, this is not valid.

答案1

得分: 1

SQL片段中的@Formula注释规则是,任何“裸露”的(未限定的)列引用都将由该公式所属实体的别名限定。

所以,例如,在这个@Formula中:

@Formula("(select upper(isbn) || ' ' || upper(a.name) from authors a where a.id=author_id)")

将被添加限定符的列是isbnauthor_id

所以在你的例子中:

  • 你应该给pos添加一个限定符以抑制这种行为,但是
  • 你应该保持idgarage_id未限定,因为它们属于汽车实体。

不过,你的代码中似乎有些令人困惑的地方。为什么要在这里再次加入car表?这看起来不太对。

英文:

The rule with the SQL fragment inside the @Formula annotation is that any "bare" (unqualified) column reference is going to be qualified by the alias of the entity the formula belongs to.

So, for example, in this @Formula:

@Formula("(select upper(isbn) || ' ' || upper(a.name) from authors a where a.id=author_id)")

The columns which are going to get a qualifier attached to them are isbn and author_id.

So in your example:

  • you should add a qualifier to pos to suppress this behavior, but
  • you should leave id and garage_id unqualified since they belong to the car entity.

However, there's something that seems rather confusing in your code. Why would you be joining back to the car table here? That doesn't look quite right.

huangapple
  • 本文由 发表于 2020年8月3日 21:32:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63230421.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定