Hibernate:使用公式进行多对一
我希望有人能帮我找到答案。
我正在使用旧数据库,无法更改任何预先存在的表,因为其他应用程序依赖于它们。
我有三个主要的现有表:A、B、C。
A 有一个引用 B 的列(多对一关系)。问题是它应该与 C 而不是 B 有关系。所以我创建了一个 *-1 映射 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
我不想为 B 或 BC 提供 Java 实体,只希望 A 和 C,并且 A 应该有一个字段 Ac
到目前为止,我已尝试使用 @Formula 注释但无济于事。
class A{
@ManyToOne
@Formula(value="select BC.c from BC where BC.b = b")
private C c;
}
这会产生以下 SQL:
select this_.c_ID from A this_
它显然失败了,因为表 A 中没有列 c_ID(为什么公式被完全忽略?)。
删除 @ManyToOne 注释会产生:
select (select BC.c from BC where BC.b = this_.b) as formula_0 from A this_
这将是完美的,除了 Hibernate 需要 BINARY 值(类 C 的序列化?)并在转换它接收的 Integer 时抛出异常。
这个 ID 对于延迟加载来说应该足够了,但是我如何告诉它这样做呢? @ManyToOne 的任何使用都会破坏公式。
如何在不更改 A、B、C 表或创建 java 类 B 或 BC 的情况下实现 AC 链接?
感谢您提供任何信息, 担
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来很像这个 bug,不幸的是,似乎没有使用注释进行修复不过,您可能会使用这些类的 xml 映射文件来处理它。
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.
这应该适用于 Hibernate 3.5.0-Beta-2+ (HHH- 4382 已修复)。
This is supposed to work in Hibernate 3.5.0-Beta-2+ (HHH-4382 has been fixed).