16

I have a table named Samples in my DB,and it has a column named baseline which is a boolean variable. I wanted to search among the rows which have baseline set as 1, so I created a view in the DB (MySQL). Now, instead of querying the Samples table, I want to query this view (names as Baselines).

Do I need to add a declaration for this view in the hibernate cfg file? Also, do I need to create another Java class named Baselines for this?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Gaurav Suman
  • 515
  • 1
  • 3
  • 17
  • You don't need a view for this purpose, you could achieve this simply by `filter`, `where` annotations. Also, you `could` use JPA. Searching and filtering on the same table are very common and shouldn't require a view. Use views in case you have complex joins. – garg10may Apr 18 '20 at 06:52

1 Answers1

18

Hibernate can treat views like it does any table. Just define an entity class based on that view (Baselines, as you say).

The most common difficulty with views is that some database engines can't handle inserts or updates on views, so be aware of that if your application tries to modify the data. I don't know if MySQL is capable of this.

An alternative to using a view is to use Hibernate Filters, which do much the same thing, but at the Hibernate session level.

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • So i would need to create a Java Class named Baselines with the same fields as the Samples class? – Gaurav Suman May 08 '12 at 09:52
  • 2
    You can add `@Immutable` to avoid updates. If you generate your database schema from entities, you might also want to use `@Subselect("select * from BaselinesView")`. – Nux Sep 28 '20 at 23:59