【发布时间】:2013-12-04 14:18:57
【问题描述】:
给定以下模型
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Super {
private int id;
private String general;
//...
}
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@PrimaryKeyJoinColumn(name="ID")
public class Sub extends Super {
private String special;
//...
}
还有以下数据
+----+----------+
| Super |
+---------------+
| id | general |
+---------------+
| 1 | General1 |
| 2 | General2 |
+----+----------+
+----+----------+
| Sub |
+---------------+
| id | special |
+---------------+
| 2 | Special2 |
+----+----------+
使用Hibernate 3.6.5,我想实现以下目标:
如果可用则返回 Sub.special,否则返回 Super.general。
所以我写了
SELECT
s.id,
CASE TYPE(s)
WHEN Sub THEN s.special
ELSE s.general
END
FROM Super s
我的预期结果是
+---------------+
| 1 | General1 |
| 2 | Special2 |
+----+----------+
但实际上返回的只是
+---------------+
| 2 | Special2 |
+----+----------+
因此结果中不包含超类型的实例。 显然,这是因为在 SELECT 子句的某处使用了子类型的属性。
任何想法,如何在不使用子查询或外连接的情况下获得上述预期结果?
EDIT3 / 澄清:
使用 CASE TYPE 并选择未绑定到子类型的内容时,一切正常。
SELECT
s.id,
CASE TYPE(s)
WHEN Sub THEN 'Hooray, I'm a sub-instance'
ELSE 'Shoot, I'm no sub-instance'
END
FROM Super s
导致
+----------------+
| 1 | Shoot... |
| 2 | Hooray... |
+----+-----------+
这里不需要静态文本,只需要子类的属性值。
- EDIT1:将@Inheritance 添加到超类和子类。
- EDIT2:添加了@PrimaryKeyJoinColumn
- EDIT3:添加了不使用子类属性 s.t. 的 SELECT。两个元组都返回。
【问题讨论】:
-
也许您可以选择使用简单的“FROM Super s”查询来选择整个对象。然后你可以在你的java代码中处理不同的情况。