Hibernate: Many-to-one using Formula

依然范特西╮ 提交于 2020-01-02 08:43:47

问题


I hope someone can help me find an answer.

I'm working with a legacy database and I can't change any of the preexisting tables, because other apps depend on them.

I have three main existing tables: A,B,C.

A has a column with reference to B(many to one relation). The problem is that it should have a relation to C not to B. So I have created a *-1 mapping BC.

Tables: A,B,C,BC (all have ID field)
A-B many to one
B-C many to one through BC
Needed:A-C without altering A,B or C

I don't want to have java entities for B or BC, just A and C, and A should have a field A.c

So far I have tried using the @Formula annotation to no avail.

class A{
  @ManyToOne
  @Formula(value="select BC.c from BC where BC.b = b")
  private C c;
}

this produces the following SQL:

select this_.c_ID from A this_

It obviously fails because there is no column c_ID in table A (why is formula ignored completely ?).

Removing the @ManyToOne annotation produces:

select (select BC.c from BC where BC.b = this_.b) as formula_0 from A this_

This would be perfect except Hibernate expects a BINARY value (the serialization of the class C ?) and throws an exception when casting the Integer it receives.

This ID should be enough for lazy loading, but how do I tell it to do that? any use of @ManyToOne breaks the formula.

How can I achieve the A-C link without altering the A,B,C tables or creating the java classes B or BC?

Thanks for any info, Dan


回答1:


Sounds very like this bug, unfortunately no fix ready using annotations, seems you might get it working with xml mapping file for those classes though.




回答2:


This is supposed to work in Hibernate 3.5.0-Beta-2+ (HHH-4382 has been fixed).



来源:https://stackoverflow.com/questions/2334676/hibernate-many-to-one-using-formula

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!