Thera是oracle视图 vendor_view 和表 vendors (供应商表仅包含名称为id的PK,以简化)
create view vendor_view as
select id as vid, 'YES' as active
from vendors;
Coresponding实体
@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 的字段生成 insert 查询?
2 回答
由于hibernate不知道您尝试插入的表是表还是视图,除非它与数据库交互 . 因此它是运行时异常,只有在Java程序与数据库交互时才能检查 .
它类似于即使表不存在它也会进行查询,但在运行时它会抛出异常 .
当相关实体的责任不属于当前实体时,您会这样做 . 例如 . 你有
Person
和Address
. 你想在Address
实体中使用Person
实体将insertable=false
,updatable=false
添加到@OneToMany relationship
,只是因为它反过来了's not the responsibility of the Address entity to create or update a Person. It' . 这不是一个技术问题,而是一个语义/自然决策 .