tom_987
tom_987

Reputation: 91

JPA query for DTYPE

I have a single table which is generated from two jpa entities (inheritance). So we have a DTYPE column generated in the database table which has entity name has values.

How do I write a jpa query to fetch data for any given entity. i.e DTYPE = 'A'?

I just tried using DTYPE in jpa query but as expected I got an error "Could not resolve property". Please let me know how to write this query.

Note - I dont want to use native query.

Update:

I have class A and subclass AA which extends A. DTYPE has two values A and AA.

When I query for A, I get all the A plus AA entities. How to exclude AA when I query for A?

Upvotes: 6

Views: 21809

Answers (4)

SCH
SCH

Reputation: 51

Simply add a simple field dtype in your parent class.

@Column(insertable = false, updatable = false)
private String dtype;

And so, you can use it in your JPQL query

Upvotes: 5

jmendiola
jmendiola

Reputation: 413

In addition of what @SCH post, and as that didn't directly work for me, using Oracle, I was getting an Exception saying that "dtype" was kind of a reserved keyword. I then did

@DiscriminatorColumn(name = "myDType")
class abstract AbstractClass{

@Column(insertable = false, updatable = false) 
private String myDType; 
[...]

That worked fine for me, as this way I could dynamically change the Type I want to query using a where condition instead of changing the FROM statement.

Upvotes: 1

Henning
Henning

Reputation: 16311

You can use the entity names in your JPA queries, the discriminator column is abstracted away.

Suppose you have two entity classes SubClassA and SubClassB, which both inherit from SuperClass, then you can query for these entites like so:

FROM SubClassA WHERE [...]

or

FROM SubClassB WHERE [...]

If you want to query for both entities, use

FROM SuperClass WHERE [...]

Upvotes: 2

cletus
cletus

Reputation: 625077

Assuming you have three entities:

  • Party (superclass)
  • Person (extends Party)
  • Organization (extends Party)

where the last two are the two entities you store with a discriminator column, your JPA-QL query should be as simple as:

select p from Person p

to get all people. JPA is smart enough to figure it out. Likewise you can do:

select p from Party p

and get all of them.

Upvotes: 3

Related Questions