Hibernate多态查询 [英] Hibernate polymorphic query

查看:108
本文介绍了Hibernate多态查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类,Person和Company,派生自另一个类Contact。它们在两个表格(Person和Company)中以多态表示。简化类看起来像这样:

  public abstract class Contact {

整数id;

public abstract String getDisplayName();

}

public class Person extends Contact {

String firstName;
字符串姓氏;

public String getDisplayName(){
return firstName ++ lastName;
}

}

公共类公司延伸联系人{

字符串名称;

public String getDisplayName(){
return name;
}

}

问题是我需要查询查找包含特定字符串的displayName的所有联系人。我无法使用displayName进行查询,因为它不是任何表的一部分。关于如何做这个查询的任何想法?

解决方案

因为你在Java类中进行连接,所以没有办法让Hibernate真的可以帮助你,对不起。它可能根本不会看到你在这个方法中做了什么,因为它实际上并不涉及持久性。



解决方案取决于你如何映射继承这些类:

如果是按层次结构表,则可以使用以下方法:为条件查询编写SQL where子句,然后使用case语句:

  s.createCriteria(Contact.class)
.add(Restrictions.sqlRestriction(?= case when type =' Person'then firstName ||''|| lastname else name end))
.list();

如果它是table per-concrete-subclass,那么你最好编写两个查询是Hibernate会做的)。


I have two classes, Person and Company, derived from another class Contact. They are represented as polymorphically in two tables (Person and Company). The simplified classes look like this:

public abstract class Contact {

  Integer id;

  public abstract String getDisplayName();

}

public class Person extends Contact {

  String firstName;
  String lastName;

  public String getDisplayName() {
    return firstName + " " + lastName;
  }

}

public class Company extends Contact {

  String name;

  public String getDisplayName() {
    return name;
  }

}

The problem is that I need to make a query finding all contacts with displayName containing a certain string. I can't make the query using displayName because it is not part of either table. Any ideas on how to do this query?

解决方案

Because you do the concatenation in the Java class, there is no way that Hibernate can really help you with this one, sorry. It can simply not see what you are doing in this method, since it is in fact not related to persistence at all.

The solution depends on how you mapped the inheritance of these classes:

If it is table-per-hierarchy you can use this approach: Write a SQL where clause for a criteria query, and then use a case statement:

s.createCriteria(Contact.class)
 .add(Restrictions.sqlRestriction("? = case when type='Person' then firstName || ' '|| lastName else name end"))
 .list();

If it is table per-concrete-subclass, then you are better of writing two queries (since that is what Hibernate will do anyway).

这篇关于Hibernate多态查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆