Search code examples
spring-boothibernatespring-data-jpahibernate-mappingdatabase-view

Spring boot create database view for entity


I have an Entity which is mapped to a database view and I want to avoid spring from creating table for it, I've tried @Immutable annotation but it's not working, also I want the program to create the view for entity from my script file if it's not created.

@Data
@Entity
@Immutable
public class ViewRequest {
    @Id
    private Long id;
    private Date createDate;
    private String requestType;
    private String customerUser;
    private Long customerUserId;
    private RequestStatusEnum requestStatus;
}

any help is appreciated.

Thanks


Solution

  • The @Subselect annotation is the only annotation in Hibernate that prevents the creation of the corresponding table for an @Entity:

    @Data
    @Entity
    @Immutable
    @Subselect("select * from VIEW_REQUEST")
    public class ViewRequest {
        @Id
        private Long id;
        private Date createDate;
        private String requestType;
        private String customerUser;
        private Long customerUserId;
        private RequestStatusEnum requestStatus;
    }
    

    Special thanks to this answer : Exclude a specific table from being created by hibernate?

    and for the view creation, you should add your script to a file called data.sql in resources folder, and the file would be automatically executed after table updates of hibernate.enter image description here