Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Please explain below queries in case of JPA @Inheritance(strategy=InheritanceType.JOINED)

 
xsunil kumar
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have two entities - Product.java and Book.java. Book is extending Product and i have defiend inheritence as @Inheritance(strategy=InheritanceType.JOINED). As per my understanding, i will create two tables :- Product and Book.

When i am trying to persist Book in the database using em.persist, it is inserting one record in Book as well as Product table.

My question is that

1. whether my undetstanding is correct or not. Means, whenever i will try to persist child class, it will insert one record in parent class also ?

2. If i will use entityManager.find method and i will pass Product class, then it will fetch child record also ?

For example:- I i will use below code


By looking in sql generated by JPA, it is doing query on Book table also. It means that JPA is fetching data from Book table. How we can get this data in our program.
Here P is ref. of Product object and Product do not have properties defined in Book class.

Only one way i am getting is to type case it like



Is there any way or is it right way to do....

3. Let suppose i have one more class called NoteBook which extends Product.
Now i am doing query like

Product p = (Product)em.find(Product.class, new Long(1));

How i can get to know, that this record means id =1 is related to Book entity or NoteBook entity.


Product.java



Book.java
 
James Sutherland
Ranch Hand
Posts: 553
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is correct. If you query for a superclass, it can return any subclass that fits the query. You can just cast to the subclass and use instanceof to check what type it is. This is just what inheritance is in Java.

There is a class discriminator (type) field defined in the root PRODUCT table, this is used to determine the type of object to build. If you only wanted instances of Product or some other class, you can use the TYPE() function in JPQL to check the type of the row.
 
xsunil kumar
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks James for such a nice description. Now i understood. Thanks a lot.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic