Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating views through hibernate

Is there any way to create a view when creating tables by using the hibernate.hbm2ddl.auto property. I am using annotation type for defining the table and its fields. Is there any property that I can use to create the view also through hibernate?

like image 382
Saif Avatar asked Mar 05 '13 04:03

Saif


2 Answers

Hibernate does not do that for you automatically. However, one of these solutions might be useful to you:

  1. Create a view in your database, and define a model with those columns using hibernate. Hibernate does not create a table for that model, if it finds this view. And the rest is just like using a real table.

  2. Hibernate does give you the ability to create (and drop) additional database objects yourself in the XML mapping files. Something like this.

    <database-object>
       <create>create or replace view yourView</create>
       <drop>drop view yourView</drop>
       <dialect-scope name='org.hibernate.dialect.Oracle9Dialect' />
    </database-object>
    

In my opinion the first solutions is way easier to handle, as I am currently using this method to treat my views.

like image 67
Matin Kh Avatar answered Sep 27 '22 20:09

Matin Kh


Another option is to put the view creation sql in a script that is run by hbm2ddl by configuring property

hibernate.hbm2ddl.import_files

Assuming that you have an entity that represents that view, you must do a drop table before creating the view, since hbm2ddl will create a table if it doesn't find an existing view by that name.

like image 30
HandyManDan Avatar answered Sep 27 '22 20:09

HandyManDan