How hibernate retrieve data from existing database

2020-03-12 03:29发布

I'm new to hibernate. My problem is that I have an Oracle database. I have a view in the database. Now I want to use hibernate to retrieve data in that view. Is there any possible solutions?

4条回答
Bombasti
2楼-- · 2020-03-12 04:01

It' very similar to mapping ordinary database table. Create an Entity and use your view name as 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 query for entities same way as you do for normal table. Working in Hibernate 4, Spring 4.

查看更多
一纸荒年 Trace。
3楼-- · 2020-03-12 04:05

we can achieve this by using @ Immutable annotation in entity class to map database view with Hibernate

For example : I have created one database view user_data which have 2 columns (id and name) and mapped user_data view in the same way as database tables.

@Entity
@Table(name = "user_data")
@Immutable
public class UserView {

    @Id
    @Column(name = "ID")
    private int ID ;

    @Column(name = "NAME")
    private String name ; 
}
查看更多
▲ chillily
4楼-- · 2020-03-12 04:12

Below Snippet can solve your problem, which has been extracted from the tutorial: Mapping Hibernate Entities 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());
    } 
查看更多
Evening l夕情丶
5楼-- · 2020-03-12 04:17

A view is from accessing data nothing different from table, a problem arises when you want to add,update or delete from view.

Please read http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/querysql.html

查看更多
登录 后发表回答