java—使用hibernate将实体Map到物化视图

pexxcrt2  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(402)

我需要将(postgresql)物化视图Map到 @Entity ,使用hibernate。如果是 hbm2ddl 配置为 update 值时,hibernate总是尝试创建新的sql表。只有当视图被物化时才会发生这种情况,否则(对于非物化视图)它就可以正常工作。
Map实体

@Entity
@Immutable
@Cache (usage=CacheConcurrencyStrategy.READ_ONLY)
@Table(name = "quasar_evaludated_function")
public class EvaluatedAuditor {

    private long id;

    private boolean qsAuditor;

    // getter setters ...

}

sql物化视图

CREATE materialized VIEW quasar_evaludated_function
AS SELECT a.id AS id,
          (SELECT Count(code)
           FROM   quasar_qs_auditor_code code
           WHERE  code.auditor_id = a.id
                  AND code.is_granted = TRUE) > 0 AS is_qs_auditor
   FROM   quasar_auditor a;

日志

ERROR 2015-01-14 21:16:17 SchemaUpdate:execute(line 261) - HHH000388: Unsuccessful: create table quasar_evaludated_function (id int8 not null, is_clinical_expert boolean, is_product_assessor_a boolean, is_product_assessor_r boolean, is_product_specialist boolean, is_qs_auditor boolean, is_responsible_clinician boolean, is_technical_expert boolean, primary key (id))
ERROR 2015-01-14 21:16:17 SchemaUpdate:execute(line 262) - ERROR: relation "quasar_evaludated_function" already exists

如果是 hbm2ddl 选项配置为 validate 引发异常。
谢谢你的帮助。

umuewwlo

umuewwlo1#

你不应该使用 hibernate.hbm2ddl.auto 那样的话。实际上,在让flywaydb自动化数据库更新过程的同时,您应该总是喜欢使用递增的数据库脚本。
因为您使用的是特定于数据库的具体化视图,所以hibernate模式生成器根本帮不了您。因此,您唯一的选择是特定于数据库的增量脚本。
您仍然可以为postgresql和内存数据库(例如hsqldb或h2)中的集成测试维护单独的脚本。

5tmbdcev

5tmbdcev2#

这不是一个好的解决方案,但它是有效的。我刚刚创建了一个新视图,它引用了一个物化视图。如果不需要自动生成模式,那么应该看看vladmihalcea的解决方案。

CREATE MATERIALIZED VIEW quasar_evaludated_function_mv AS select 
                a.id as id,
                (select count(f) from quasar_qs_auditor_code f where  f.auditor_id = a.id and f.is_granted = true) >  0 as is_qs_auditor,
                (select count(f) from quasar_product_assessor_a_code f where  f.auditor_id = a.id and f.is_granted = true) >  0 as is_product_assessor_a,
                (select count(f) from quasar_product_assessor_r_code f where  f.auditor_id = a.id and f.is_granted = true) >  0 as is_product_assessor_r, 
                (select count(f) from quasar_product_specialist_code f where  f.auditor_id = a.id and f.is_granted = true) >  0 as is_product_specialist,
                (select count(f) from quasar_technical_expert_code f where  f.auditor_id = a.id and f.is_granted = true) >  0 as is_technical_expert,
                (select count(f) from quasar_clinical_expert_code f where  f.auditor_id = a.id and f.is_granted = true) >  0 as is_clinical_expert, 
                (select count(f) from quasar_responsible_clinician_code f where  f.auditor_id = a.id and f.is_granted = true) >  0 as is_responsible_clinician
                from quasar_auditor a;

    CREATE VIEW quasar_evaludated_function  AS SELECT mv.* from quasar_evaludated_function_mv mv;

相关问题