【问题标题】:Column in the Postgres database table not being populated automaticallyPostgres 数据库表中的列未自动填充
【发布时间】:2012-05-22 21:12:53
【问题描述】:

我正在使用休眠连接到 Postgres 数据库。在数据库中有一个表,其中一列设置为存储记录插入该表时的当前时间。当我从 Postgres 界面插入记录时,当前时间会自动填充。

但是当我尝试从 Hibernate 插入记录时,数据库不会自动将记录插入到当前时间列中。

Query dateQuery=session.createQuery("select b.boilerPlateContent from Boiler_Plates b join b.bt_contracts c where c.contractId=:val order by b.boilerPlateContent desc)").setEntity("val",ct);
Iterator dateIterator = dateQuery.list().iterator();
String latestBoilerPlate=(String)dateIterator.next();
System.out.println(latestBoilerPlate);
Pattern p=Pattern.compile("\\d+");
Matcher m=p.matcher(latestBoilerPlate);
while(m.find()){
 lastEntered=m.group();
 nextBoilerPlateNumber=Integer.parseInt(m.group());
}
nextBoilerPlateNumber++;
Boiler_Plates  bp=new Boiler_Plates();
bp.setBoiler_plate_id(boilerPlateId);
boilerPlateText="bp"+nextBoilerPlateNumber;
bp.setBoilerPlateContent(boilerPlateText);
bp.setBoilerPlateName("Test");
//bp.setInsertTime();
bp.setContract(ct);
session.save(bp);
tx.commit(); 

【问题讨论】:

    标签: hibernate postgresql insert


    【解决方案1】:

    您似乎正在尝试进行审核。为此,您应该使用非常完善的解决方案,而不是自己动手。请参阅 enverstrigger examples on the PostgreSQL wiki@PrePersist, @PreUpdate, and entity listeners 的 JPA 审计支持。更好的是,使用@Embeddable 实体和@EntityListener,这样您就可以重用您的审计代码。

    您尚未指定如何自动设置您的列。

    如果您设置了 DEFAULT,那么 Hibernate 会为 INSERT 上的所有列指定值,因此 DEFAULT 将不会被使用。您需要让 Hibernate 避免设置列或明确指定关键字 DEFAULT 作为列值 - 您可以通过将其映射为 insertable=false,updatable=false 来做到这一点。或者,您需要让 Hibernate 直接插入您想要的值。

    另一个选项是使用ON INSERT FOR EACH ROW 触发器来设置列的值。这使您可以从 PL/PgSQL 设置值,无论有人在 INSERT 时为该列指定什么。

    这里是another entity listener example

    【讨论】:

    • 您的回答帮助我解决了问题。我将属性中的 insert 属性设置为 false 并且效果很好。
    【解决方案2】:

    正如已经指出的那样,您最初问题中的信息非常缺乏。但是假设“插入记录时自动填充当前时间”意味着您在该列上定义了 DEFAULT,则 DEFAULT 值仅在插入语句中未引用该列时才生效。 Hibernate 默认会引用插入语句中的所有列。但是,您可以更改该行为。我认为您正在寻找类似这样的映射:

    @Entity
    public class Boiler_Plates {
        ...
        @Temporal(TemporalType.TIMESTAMP)
        @Generated(GenerationTime.INSERT) 
        @Column(insertable = false)
        Date insertTime
    }
    

    @Column(insertable = false) 表示不在 INSERT 语句中包含该列。 @Generated(GenerationTime.INSERT) 表示在执行 INSERT 后重新读取该列的状态以查找生成的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      • 2018-06-13
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多