Friday, September 16, 2016

Add entity with InheritanceType.JOINED to native query

Leave a Comment

I am struggling to get native queries to work with InheritanceType.JOINED. From the Hibernate documentation I have found:

13.1.6. Handling inheritance

Native SQL queries which query for entities that are mapped as part of an inheritance must include all properties for the baseclass and all its subclasses.

Using the following two entities:

@Data @Entity @Table(name = "my_super") @EqualsAndHashCode(of = {"id"}) @Inheritance(strategy = InheritanceType.JOINED) public abstract class MySuper {      @Id     @Column(name = "id")     @GeneratedValue(strategy = GenerationType.SEQUENCE)     private long id;  } 

And:

@Data @Entity @Table(name = "my_sub_a") @EqualsAndHashCode(callSuper = true) public class MySubA extends MySuper {      @Column(name = "x")     private int x;  } 

When I try to create a native query using:

Object actual = session     .createNativeQuery("SELECT {s.*} FROM my_super {s} LEFT JOIN my_sub_a {a} USING (id)")     .addEntity("s", MySuper.class)     .getSingleResult(); 

It translates to the query:

SELECT s.id as id1_1_0_, s_1_.x as x1_0_0_, case when s_1_.id is not null then 1 when s.id is not null then 0 end as clazz_0_ FROM my_super s LEFT JOIN my_sub_a  a  USING (id)  

And then fails with:

javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not prepare statement Caused by: org.hibernate.exception.SQLGrammarException: could not prepare statement Caused by: org.h2.jdbc.JdbcSQLException: Column "S_1_.X" not found; SQL statement: 

So we observe the alias injection doing its work, figuring out that it may need the x column of my_sub_a as well. It is however unable to figure out the alias for my_sub_a. How should my code be modified so that this alias is connected properly as well?

My code is available at https://gist.github.com/JWGmeligMeyling/51e8a305f3c268eda473511e202f76e8 for easy reproduction of my issue.

(I am aware that this query can easily be expressed in JPQL or HQL as well, and can even be achieved using the EntityManager and Session API's. I do however want to use this in a more complex query, that I simplified to all details required for this question).

0 Answers

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment