Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast Entity inside a query

Tags:

jpa

jpql

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!

like image 296
Saveriu CIANELLI Avatar asked Jun 25 '26 16:06

Saveriu CIANELLI


2 Answers

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 
like image 144
Panchitoboy Avatar answered Jun 30 '26 08:06

Panchitoboy


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

like image 43
Ondrej Bozek Avatar answered Jun 30 '26 08:06

Ondrej Bozek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!