gpt4 book ai didi

java - JPA 可通过 View 和 secondaryTable 进行插入和更新

转载 作者:太空宇宙 更新时间:2023-11-04 13:08:20 24 4
gpt4 key购买 nike

Thera是oracle View vendor_view和表vendors(为简单起见,vendors表仅包含带有名称id的PK)

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

对应实体

@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 查询?

最佳答案

因为 hibernate 不知道您尝试插入的表是表还是 View ,除非它与数据库交互。所以这是运行时异常,只有当Java程序与数据库交互时才能检查。

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

关于java - JPA 可通过 View 和 secondaryTable 进行插入和更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34208122/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com