Is it possible to map a model to a database view instead of a table? If it is, how to do it?
Asked
Active
Viewed 1,057 times
1 Answers
1
Yes. It is very simple. If you have a view called EXAMPLE_VIEW, you just need to do:
@Entity
@Table(name = "EXAMPLE_VIEW")
public class Example implements Serializable {
}
The columns inside the Example class you map exactly like you map a table. For Hibernate, a view is like a table

Dherik
- 17,757
- 11
- 115
- 164
-
You need a primary key for Hibernate work properly. An alternative is create a composite key with some of the columns when you map this view. If even this is not possible, you will need to use JDBC or native query, hibernate mapping is not an option. – Dherik Aug 27 '14 at 03:25
-
how do I add a primary key to my VIEW? – lxcky Aug 27 '14 at 03:45
-
You can use EmbeddedId to do this. Read this answer to know how: http://stackoverflow.com/a/3588400/2387977 – Dherik Aug 27 '14 at 13:41