How does hibernate retrieve data from an existing database view?
Below snippet might solve your problem which was pulled from the tutorial: Mapping Hibernate Objects to Views
Database Query
CREATE OR REPLACE VIEW cameron AS
SELECT last_name AS surname
FROM author
WHERE first_name = 'Cameron';
view entity
@Entity
@NamedNativeQuery(name = "findUniqueCameronsInOrder", query = "select * from cameron order by surname", resultClass = Cameron.class)
public class Cameron implements java.io.Serializable {
private static final long serialVersionUID = 8765016103450361311L;
private String surname;
@Id
@Column(name = "SURNAME", nullable = false, length = 50)
public String getSurname() {
return surname;
}
public void setSurname(final String surname) {
this.surname = surname;
}
}
Hibernate mapping file.
<mapping class="examples.hibernate.spring.query.domain.Cameron" />
finally some test !...
@Test
public void findTheCameronsInTheView() throws Exception {
final List<Cameron> camerons = findUniqueCameronsInOrder();
assertEquals(2, camerons.size());
final Cameron judd = camerons.get(0);
final Cameron mcKenzie = camerons.get(1);
assertEquals("Judd", judd.getSurname());
assertEquals("McKenzie", mcKenzie.getSurname());
}
source to share
The view is that data access is no different from a table, a problem arises when you want to add, update or remove from a view.
Please read http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/querysql.html
source to share
It is very similar to displaying a regular database table. Create an entity and use your view name as the table name.
@Entity
@Table(name = "rc_latest_offer_details_view")
public class OfferLatestDetailsViewEntity {
@Id
@Column(name = "FK_OFFER_ID")
private int offerId;
@Column(name = "MAX_CHANGED_DTM")
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime changedDateTime;
private BigDecimal price;
...
}
Then the query for the objects is the same as for a regular table. Working in Hibernate 4, Spring 4.
source to share
we can achieve this by using the @Immutable annotation in the entity class to map the database view to Hibernate
For example: I created one database view user_data which has 2 columns (id and name) and a mapped user_data view just like the database tables.
@Entity
@Table(name = "user_data")
@Immutable
public class UserView {
@Id
@Column(name = "ID")
private int ID ;
@Column(name = "NAME")
private String name ;
}
source to share