Hibernate: Many-to-one using Formula

2019-05-17 01:43发布

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

2条回答
仙女界的扛把子
2楼-- · 2019-05-17 02:14

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

查看更多
来,给爷笑一个
3楼-- · 2019-05-17 02:27

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.

查看更多
登录 后发表回答