我有一张这样的 table :
id | name | score
使用 Hibernate 通过 XML 映射到 POJO。我只需要 order by
中的得分列 - HQL 中的子句。分数列的值由算法计算,并通过 SQL 批处理 (JDBC) 每 24 小时更新一次。所以我不想用我在运行时不需要的属性污染我的 POJO。
对于单个列可能不是问题,但我有几个不同的分数列。 有没有一种方法可以映射仅供 HQL 使用的属性?
例如像这样:
<property name="score" type="double" ignore="true"/>
所以我仍然可以这样做:
from Pojo p order by p.score
但我的 POJO 实现可能如下所示:
public class Pojo
{
private long id;
private String name;
// ...
}
没有为 score
提供 Setter 或向实现中添加属性。
为 Java 使用最新的 Hibernate 版本。
更新:
在一个完美的世界中,它可以像这样完成(感谢 Pascal Thivent ):
<property name="score" access="noop" insert="false" update="false"/>
但在我们的现实世界中存在a bug since years似乎没有人关心。那么有人对解决方法有建议吗?
最佳答案
您可以在映射中使用 access="noop"
来指定仅查询属性(这是一个 secret 的、未记录的功能,请参阅 HHH-552):
<property name="score" access="noop" insert="false" update="false" ... />
更新:澄清一下,使用以下实体:
public class EntityWithHqlOnlyProperty implements Serializable {
private Long id;
private String name;
//...
}
还有这个映射:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.stackoverflow.q2812672.EntityWithHqlOnlyProperty" table="EntityWithHqlOnlyProperty">
<id name="id" type="java.lang.Long">
<column name="id" />
<generator class="assigned" />
</id>
<property name="name" type="string">
<column name="name" not-null="true" />
</property>
<property name="score" type="double" access="noop" insert="false" update="false"/>
</class>
</hibernate-mapping>
以下片段:
Query q = session.createQuery("from EntityWithHqlOnlyProperty e order by e.score");
List<EntityWithHqlOnlyProperty> resultList = q.list();
assertNotNull(resultList);
生成以下 SQL:
select
entitywith0_.id as id6_,
entitywith0_.name as name6_,
entitywith0_.score as score6_
from
EntityWithHqlOnlyProperty entitywith0_
order by
entitywith0_.score
在我的现实世界中,测试刚刚通过。这已经在 Derby 和 HSQLDB 上使用 Hibernate Core 3.3.2.GA 进行了测试。换句话说,它可以在我的机器上运行 (c)。
如果它不适合你 - 我并不是故意粗鲁但是 - 在一个完美的世界中 你应该提供一个允许重现的测试用例 HHH-2925按照 3 年以上的要求。提供一种重现问题的方法(我不能)会大大增加解决问题的机会。
关于java - 如何映射一个仅供 HQL 使用的属性(在 Hibernate 中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2812672/