在查询中强制转换实体 [英] Cast Entity inside a query

查看:48
本文介绍了在查询中强制转换实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在jpql查询中强制转换实体的方法.

I'm looking for a way to cast an entity inside a jpql query.

示例:

@Entity
class Topic {
  @OneToMany
  List<AbstractMessage> messages;
}

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
abstract class AbstractMessage {
   String content;
}

@Entity
class MessageType1 extends AbstractMessage {
   String att1;
}

@Entity
class MessageType2 extends AbstractMessage {
   Integer att2;
}

我正在尝试收集所有一个或多个消息的类型为MessageType2且att2 = 1的所有Topic.

I'm trying to collect all Topic where one or more of its messages have the type MessageType2 and have att2 = 1.

以下是我对jpql查询的建议:

Here is my suggestion as a jpql query:

select t from Topic t left outer join t.messages on (Type(t) = MessageType2)
where t.att2 = 1 

我不认为此查询有效,因为JPA没有加入MessageType2表.

I don't think this query works because JPA doesn't join the MessageType2 table.

有没有办法做到这一点,或者我必须进行本地查询?

Is there a way to do that or I have to make a native query?

谢谢!

推荐答案

您可以模拟CAST: http://en.wikibooks.org/wiki/Java_Persistence/Querying#Joining.2C_querying_on_a_OneToMany_lationship

You can simulate the CAST: http://en.wikibooks.org/wiki/Java_Persistence/Querying#Joining.2C_querying_on_a_OneToMany_relationship

SELECT t FROM Topic t JOIN t.messages m, MessageType2 y WHERE m = y AND y.att2 = 1 

这篇关于在查询中强制转换实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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