JPA可插入和可更新的View和SecondaryTable

时间:2015-12-10 17:27:12

标签: java hibernate jpa

Thera是oracle视图 vendor_view 和表 供应商 (供应商表仅包含名称为id的PK,以简化)

create view vendor_view as
    select id as vid, 'YES' as active
    from vendors;

Coresponding entity

@Entity
@Table(name = "vendors")
@SecondaryTable(name = "vendor_view", pkJoinColumns = {@PrimaryKeyJoinColumn(name = "vid", referencedColumnName = "id")})
public class Vendor {

    @Id
    private Long id;

    @Column(table = "vendor_view", name = "vid", insertable = false, updatable = false)
    private Long vid;

    @Column(table = "vendor_view", name = "active", insertable = false, updatable = false)
    private String active;


     getter and setter....
}

当我尝试坚持新的供应商实体时,面对问题:

org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [insert into vendor_view (vid) values (?)]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
            at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:238)
.....
Caused by: org.hsqldb.HsqlException: INSERT, UPDATE, DELETE or TRUNCATE not permitted for table or view
            at org.hsqldb.error.Error.error(Unknown Source)

JPA实施是Hibirnate 问题是Hibirnate为标记为 insertable = false,updatable = false 的字段生成 插入 查询的原因?

2 个答案:

答案 0 :(得分:0)

由于hibernate不知道您尝试插入的表是表还是视图,除非它与数据库交互。因此它是运行时异常,只有在Java程序与数据库交互时才能检查。

类似于即使表不存在它也会进行查询但在运行时会抛出异常。

答案 1 :(得分:0)

creating/udpating相关实体的责任不在当前实体中时,您就会这样做。例如。您有PersonAddress。您希望将insertable=falseupdatable=false添加到@OneToMany relationship实体中Person实体的Address,只是因为它不是Address实体负责创建或更新Person。反之亦然。这不是技术性的,而是更多的语义/自然决定。