Cast Entity inside a query

孤者浪人 提交于 2021-02-07 20:55:26

问题


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

Example:

@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;
}

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

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 

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?

Thanks!


回答1:


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 



回答2:


Cleaner solution would be to use JPA 2.1 TREAT:

SELECT t FROM Topic t JOIN TREAT(t.messages AS MessageType2) m WHERE m.att2 = 1

http://hantsy.blogspot.cz/2013/12/jpa-21-treat.html



来源:https://stackoverflow.com/questions/28881957/cast-entity-inside-a-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!