Upload an object from a view to JPA / Hibernate

I have an application that uses Spring and Hibernate. There are some views in my database that I need to load in some objects. Therefore, I am trying to fulfill my own request and load the class with the data obtained from the view:

//In my DAO class (@Repository) public List<MyClass> findMyEntities(){ Query query = em.createNativeQuery("SELECT * FROM V_myView", MyClass.class); return query.getResultList(); } 

and MyClass has the same fields as the column names of the view.

The problem is that Hibernate cannot recognize MyClass because it is not an entity (it is not annotated with @Entity)

org.hibernate.MappingException: unknown object

If I put MyClass as an entity, the system will attempt to create / update a table for this object, because I configured it:

<property name="hibernate.hbm2ddl.auto" value="update"/>

So, I get into the following questions:

  • Is it possible to disable "hibernate.hbm2ddl.auto" for only one object?
  • Is there a way to load data from a view into a class without an entity?
  • If not, what would be the best way in my case for loading data from a view into a class in sleep mode?

thanks

+4
source share
3 answers

You can use axtavt solution . You can also simply execute your query and convert List<Object[]> , which will be explicitly returned in List<MyClass> . Or you can display your view as a read-only object, which is probably the best solution, since it will allow you to create associations with other tables, query through JPQL, criteria, etc.

In my opinion, hibernate.hbm2ddl.auto should only be used for fast n 'dirty prototypes. Use the hibernate tools to create an SQL file that allows you to create a schema, and modify it to remove the creation of the view. In any case, if it is configured to update, should you not skip creating the table since it already exists (as a view)?

+2
source

Posted on your class

 @Entity @Immutable @Subselect(QUERY) public MyClass {....... } 

Hibernate executes a query to retrieve data, but does not create a table or view. The disadvantage of this is that it is read-only.

+7
source

You can use AliasToBeanResultTransformer . Since this is a special Hibernate function, you need to access the base Hibernate Session :

 return em.unwrap(Session.class) .createSQLQuery("...") .setResultTransformer(new AliasToBeanResultTransformer(MyClass.class)) .list(); 
+1
source

Source: https://habr.com/ru/post/1387373/


All Articles