Hibernate 未自动填充Postgres数据库表中的列

Hibernate 未自动填充Postgres数据库表中的列,hibernate,postgresql,insert,Hibernate,Postgresql,Insert,我正在使用hibernate连接Postgres数据库。在数据库中有一个表,其中一列被设置为存储记录插入该表时的当前时间。当前时间在我从Postgres界面插入记录时自动填充 但当我尝试从Hibernate插入记录时,数据库不会自动将记录插入到当前时间列中 Query dateQuery=session.createQuery("select b.boilerPlateContent from Boiler_Plates b join b.bt_contracts c where c.contr

我正在使用hibernate连接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(); 

您似乎正在尝试进行审核。有非常完善的解决方案,您应该使用,而不是滚动自己的解决方案。请参阅,以及JPA审计支持。更好的是,使用@Embeddeble实体和@EntityListener,这样您就可以重用审计代码

您尚未指定自动设置列的方式

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

另一个选项是为每行使用插入时的
触发器来设置列的值。这使您可以从PL/PgSQL设置值,而不管有人在插入时为列指定了什么


以下是。

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

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

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

您的回答帮助我解决了这个问题。我将属性中的insert属性设置为false,效果很好。