Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load Entity from View in JPA/Hibernate

I have an application which uses Spring and Hibernate. In my database there are some views that I need to load in some entities. So I'm trying to execute a native query and load the class withthe data retrieved 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 can't recognize MyClass because it's not an entity (it's not annotated with @Entity)

org.hibernate.MappingException: Unknown entity

If I put MyClass as an entity the system will put try to create/update a table for that entity, because I have configured it :

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

So I come into these questions:

  1. Can I disable "hibernate.hbm2ddl.auto" just for a single entity?
  2. Is there any way to load the data from a view into a non-entity class?
  3. If not, what would be the best way in my case for loading the data from a view into a class in hibernate?

Thanks

like image 271
Javi Avatar asked Dec 28 '22 08:12

Javi


2 Answers

Placed on your class

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

Hibernate execute the query to retrieve data, but not create the table or view. The downside of this is that it only serves to make readings.

like image 148
Jhonathan Avatar answered Dec 30 '22 10:12

Jhonathan


You may use axtavt solution. You may also just execute your query, and transform the List<Object[]> it will return into a List<MyClass> explicitely. Or you may map your view as a read-only entity, which is probably the best solution, because it would allow for associations with other tables, querying through JPQL, Criteria, etc.

In my opinion, hibernate.hbm2ddl.auto should only be used for quick n' dirty prototypes. Use the hibernate tools to generate the SQL file allowing to create the schema, and modify it to remove the creation of the view. Anyway, if it's set to update, shouldn't it skip the table creation since it already exists (as a view)?

like image 41
JB Nizet Avatar answered Dec 30 '22 10:12

JB Nizet