在使用Spring、Hibernate和PostgreSQL进行插入操作时,在列中生成一个时间戳。

huangapple go评论74阅读模式
英文:

Generate a timestamp in a column while inserting in Spring, Hibernate and PostgreSQL

问题

我正在学习Spring,Hibernate和PostgreSQL。我有一个实体,其中包含时间戳字段。数据库中的这个时间戳列被称为datecreated

这个时间戳应该自动生成,但实际上没有。在插入记录时,只生成了空值,而不是日期。

我尝试了许多互联网上的解决方案组合,但都没有成功。我尝试了这些:


@CreationTimestamp
private Date dateCreated;

@CreationTimestamp
@Column
private Date dateCreated;

@CreationTimestamp
@Column
private Date dateCreated = new Date();

@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column
private Date dateCreated = new Date();

@Temporal(TemporalType.TIMESTAMP)
@Column
private Date dateCreated = new Date();

@Temporal(TemporalType.TIMESTAMP)
@Column(updatable = false)
private Date dateCreated = new Date();

@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(updatable = false)
private Date dateCreated = new Date();

@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(updatable = false)
private Date dateCreated;

@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(updatable = false)
private Date dateCreated;

@PrePersist
protected void onCreate() {
    dateCreated = new Date();
}

这是我得到的结果:

在使用Spring、Hibernate和PostgreSQL进行插入操作时,在列中生成一个时间戳。

如何使其生成时间戳?

这里有一些项目文件:Image.java模型、pom.xml、import.sql DDL、hibernate.cfg.xml文件:

Image.java

package com.howtodoinjava.demo.spring.domain;

import javax.persistence.*;
import java.util.Date;
import org.hibernate.annotations.CreationTimestamp;

@Entity
@Table(name = "images")
public class Image {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, length = 300)
    private String title;

    @Column(nullable = false)
    private String url;

    @Column(nullable = false)
    private String author;

    @CreationTimestamp
    @Column
    private Date dateCreated = new Date();

    // getter and setter methods...

    @Override
    public String toString() {
        //...
    }
}

pom.xml

<!-- ... -->

import.sql

-- ...

hibernate.cfg.xml

<!-- ... -->
英文:

I am learning Spring, Hibernate and PostgreSQL. I have an entity that has the field of the timestamp. A database column of this timestamp is called datecreated.

This timestamp should be generated automatically but is not. While inserting a record, null value is generated only, instead of the date.

I tried many combination of solutions that are on internet, but I not succeeded. I tried this:


@CreationTimestamp
private Date dateCreated;

@CreationTimestamp
@Column
private Date dateCreated;

@CreationTimestamp
@Column
private Date dateCreated = new Date();

@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column
private Date dateCreated = new Date();

@Temporal(TemporalType.TIMESTAMP)
@Column
private Date dateCreated = new Date();

@Temporal(TemporalType.TIMESTAMP)
@Column(updatable = false)
private Date dateCreated = new Date();

@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(updatable = false)
private Date dateCreated = new Date();

@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(updatable = false)
private Date dateCreated;

@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(updatable = false)
private Date dateCreated;

@PrePersist
protected void onCreate() {
    dateCreated = new Date();
}

This is what I am getting:
在使用Spring、Hibernate和PostgreSQL进行插入操作时,在列中生成一个时间戳。

How to make it generate the timestamps?
Here you are a project files Image.java model, pom.xml, import.sql ddl, hibernate.cfg.xml files:

Image.java

package com.howtodoinjava.demo.spring.domain;

import javax.persistence.*;
import java.util.Date;
import org.hibernate.annotations.CreationTimestamp;

@Entity
@Table(name = &quot;images&quot;)
public class Image {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, length = 300)
    private String title;

    @Column(nullable = false)
    private String url;

    @Column(nullable = false)
    private String author;

    @CreationTimestamp
    @Column
    private Date dateCreated = new Date();

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Date getDate() {
        return dateCreated;
    }

    public void setDate(Date dateCreated) {
        this.dateCreated = dateCreated;
    }

    public Image() {}

    public Image(Long id, String title, String url, String author) {
        this.id = id;
        this.title = title;
        this.url = url;
        this.author = author;
    }

    @Override
    public String toString() {
        return &quot;Post{&quot; +
                &quot;id=&quot; + id +
                &quot;, title=&#39;&quot; + title + &#39;\&#39;&#39; +
                &quot;, url=&#39;&quot; + url + &#39;\&#39;&#39; +
                &quot;, author=&quot; + author +
                &quot;, date=&quot; + dateCreated +
                &#39;}&#39;;
    }
}

pom.xml

&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
&lt;groupId&gt;com.bitMiners&lt;/groupId&gt;
&lt;artifactId&gt;pdf-app&lt;/artifactId&gt;
&lt;version&gt;0.0.1&lt;/version&gt;
&lt;packaging&gt;war&lt;/packaging&gt;
&lt;properties&gt;
&lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;
&lt;aspect.version&gt;1.9.2&lt;/aspect.version&gt;
&lt;jackson.version&gt;2.9.8&lt;/jackson.version&gt;
&lt;hibernate.version&gt;5.4.2.Final&lt;/hibernate.version&gt;
&lt;hibernate.validator.version&gt;6.0.13.Final&lt;/hibernate.validator.version&gt;
&lt;c3p0.version&gt;0.9.5.2&lt;/c3p0.version&gt;
&lt;/properties&gt;
&lt;dependencies&gt;
&lt;!-- servlets and jps --&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.servlet&lt;/groupId&gt;
&lt;artifactId&gt;jstl&lt;/artifactId&gt;
&lt;version&gt;1.2&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.servlet&lt;/groupId&gt;
&lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt;
&lt;version&gt;4.0.1&lt;/version&gt;
&lt;scope&gt;provided&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.apache.tiles&lt;/groupId&gt;
&lt;artifactId&gt;tiles-extras&lt;/artifactId&gt;
&lt;version&gt;3.0.8&lt;/version&gt;
&lt;exclusions&gt;
&lt;exclusion&gt;
&lt;groupId&gt;org.slf4j&lt;/groupId&gt;
&lt;artifactId&gt;jcl-over-slf4j&lt;/artifactId&gt;
&lt;/exclusion&gt;
&lt;exclusion&gt;
&lt;groupId&gt;jboss&lt;/groupId&gt;
&lt;artifactId&gt;javassist&lt;/artifactId&gt;
&lt;/exclusion&gt;
&lt;/exclusions&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;commons-fileupload&lt;/groupId&gt;
&lt;artifactId&gt;commons-fileupload&lt;/artifactId&gt;
&lt;version&gt;1.3.3&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.apache.commons&lt;/groupId&gt;
&lt;artifactId&gt;commons-io&lt;/artifactId&gt;
&lt;version&gt;1.3.2&lt;/version&gt;
&lt;/dependency&gt;
&lt;!--hibernate--&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.hibernate&lt;/groupId&gt;
&lt;artifactId&gt;hibernate-core&lt;/artifactId&gt;
&lt;version&gt;${hibernate.version}&lt;/version&gt;
&lt;exclusions&gt;
&lt;exclusion&gt;
&lt;groupId&gt;org.javassist&lt;/groupId&gt;
&lt;artifactId&gt;javassist&lt;/artifactId&gt;
&lt;/exclusion&gt;
&lt;/exclusions&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.hibernate&lt;/groupId&gt;
&lt;artifactId&gt;hibernate-entitymanager&lt;/artifactId&gt;
&lt;version&gt;${hibernate.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- Hibernate-C3P0 Integration --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.hibernate&lt;/groupId&gt;
&lt;artifactId&gt;hibernate-c3p0&lt;/artifactId&gt;
&lt;version&gt;${hibernate.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- c3p0 --&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.mchange&lt;/groupId&gt;
&lt;artifactId&gt;c3p0&lt;/artifactId&gt;
&lt;version&gt;${c3p0.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- validation --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.hibernate.validator&lt;/groupId&gt;
&lt;artifactId&gt;hibernate-validator&lt;/artifactId&gt;
&lt;version&gt;${hibernate.validator.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;mysql&lt;/groupId&gt;
&lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
&lt;version&gt;5.1.34&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- for rest services --&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
&lt;artifactId&gt;jackson-databind&lt;/artifactId&gt;
&lt;version&gt;${jackson.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.servlet.jsp&lt;/groupId&gt;
&lt;artifactId&gt;javax.servlet.jsp-api&lt;/artifactId&gt;
&lt;version&gt;2.3.3&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- For Aop --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.aspectj&lt;/groupId&gt;
&lt;artifactId&gt;aspectjrt&lt;/artifactId&gt;
&lt;version&gt;${aspect.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.aspectj&lt;/groupId&gt;
&lt;artifactId&gt;aspectjweaver&lt;/artifactId&gt;
&lt;version&gt;${aspect.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- To Send Email --&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.sun.mail&lt;/groupId&gt;
&lt;artifactId&gt;javax.mail&lt;/artifactId&gt;
&lt;version&gt;1.5.4&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
&lt;artifactId&gt;spring-security-core&lt;/artifactId&gt;
&lt;version&gt;5.2.0.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt;
&lt;version&gt;5.2.0.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-tx&lt;/artifactId&gt;
&lt;version&gt;5.2.0.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-orm&lt;/artifactId&gt;
&lt;version&gt;5.2.0.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
&lt;artifactId&gt;spring-security-web&lt;/artifactId&gt;
&lt;version&gt;5.2.0.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
&lt;artifactId&gt;spring-security-config&lt;/artifactId&gt;
&lt;version&gt;5.2.0.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;!--logging--&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.apache.logging.log4j&lt;/groupId&gt;
&lt;artifactId&gt;log4j-core&lt;/artifactId&gt;
&lt;version&gt;2.8.2&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.apache.logging.log4j&lt;/groupId&gt;
&lt;artifactId&gt;log4j-api&lt;/artifactId&gt;
&lt;version&gt;2.8.2&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-web --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.apache.logging.log4j&lt;/groupId&gt;
&lt;artifactId&gt;log4j-web&lt;/artifactId&gt;
&lt;version&gt;2.13.3&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.slf4j&lt;/groupId&gt;
&lt;artifactId&gt;slf4j-simple&lt;/artifactId&gt;
&lt;version&gt;1.7.30&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- PostgreSQL --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.postgresql&lt;/groupId&gt;
&lt;artifactId&gt;postgresql&lt;/artifactId&gt;
&lt;version&gt;42.2.16&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-context-support&lt;/artifactId&gt;
&lt;version&gt;5.1.3.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-taglibs --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
&lt;artifactId&gt;spring-security-taglibs&lt;/artifactId&gt;
&lt;version&gt;5.1.2.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;build&gt;
&lt;!-- To define the plugin version in your parent POM --&gt;
&lt;pluginManagement&gt;
&lt;plugins&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;
&lt;version&gt;2.22.1&lt;/version&gt;
&lt;/plugin&gt;
&lt;/plugins&gt;
&lt;/pluginManagement&gt;
&lt;plugins&gt;
&lt;!-- To use the plugin goals in your POM or parent POM --&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;
&lt;version&gt;2.22.1&lt;/version&gt;
&lt;/plugin&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
&lt;configuration&gt;
&lt;source&gt;1.8&lt;/source&gt;
&lt;target&gt;1.8&lt;/target&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt;
&lt;version&gt;3.2.2&lt;/version&gt;
&lt;/plugin&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
&lt;/plugin&gt;
&lt;/plugins&gt;
&lt;/build&gt;
&lt;/project&gt;

import.sql

This file is placed in a path: src/main/resources/import.sql and it is automatically executed when running the project. This is taken from a tutorial https://dzone.com/articles/spring-security-5-form-login-with-database-provide

-- ...
INSERT INTO images (title, url, author) VALUES (&#39;lanszaft&#39;, &#39;https://i.imgur.com/sZ64fVI.jpg&#39;, &#39;Oskar Kamiński&#39;);
INSERT INTO images (title, url, author) VALUES (&#39;kobieta w kapeluszu&#39;, &#39;https://i.imgur.com/spMsvHe.png&#39;, &#39;Pablo Picasso&#39;);

hibernate.cfg.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE hibernate-configuration PUBLIC
&quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&quot;
&quot;http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd&quot;&gt;
&lt;hibernate-configuration&gt;
&lt;session-factory&gt;
&lt;property name=&quot;hibernate.archive.autodetection&quot;&gt;class,hbm&lt;/property&gt;
&lt;property name=&quot;hibernate.show_sql&quot;&gt;true&lt;/property&gt;
&lt;property name=&quot;hibernate.connection.url&quot;&gt;jdbc:postgresql://localhost:5432/postgres&lt;/property&gt; &lt;!-- BD Mane --&gt;
&lt;property name=&quot;hibernate.connection.driver_class&quot;&gt;org.postgresql.Driver&lt;/property&gt; 
&lt;property name=&quot;hibernate.connection.username&quot;&gt;user32&lt;/property&gt;
&lt;property name=&quot;hibernate.connection.password&quot;&gt;pa$$word&lt;/property&gt;
&lt;property name=&quot;hibernate.dialect&quot;&gt;org.hibernate.dialect.PostgreSQL95Dialect&lt;/property&gt;
&lt;property name=&quot;hibernate.connection.pool.size&quot;&gt;1&lt;/property&gt;
&lt;property name=&quot;hibernate.hbm2ddl.auto&quot;&gt;create&lt;/property&gt;
&lt;property name=&quot;hibernate.enable_lazy_load_no_trans&quot;&gt;true&lt;/property&gt;
&lt;property name=&quot;hibernate.jdbc.lob.non_contextual_creation&quot;&gt;true&lt;/property&gt;
&lt;property name=&quot;hibernate.c3p0.min_size&quot;&gt;5&lt;/property&gt;
&lt;property name=&quot;hibernate.c3p0.max_size&quot;&gt;20&lt;/property&gt;
&lt;property name=&quot;hibernate.c3p0.acquire_increment&quot;&gt;2&lt;/property&gt;
&lt;property name=&quot;hibernate.c3p0.timeout&quot;&gt;1800&lt;/property&gt;
&lt;property name=&quot;hibernate.c3p0.max_statements&quot;&gt;150&lt;/property&gt;
&lt;mapping class=&quot;com.howtodoinjava.demo.spring.domain.User&quot;/&gt;
&lt;mapping class=&quot;com.howtodoinjava.demo.spring.domain.Authority&quot;/&gt;
&lt;mapping class=&quot;com.howtodoinjava.demo.spring.domain.AuthorityType&quot;/&gt;
&lt;mapping class=&quot;com.howtodoinjava.demo.spring.domain.Image&quot;/&gt;
&lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;

答案1

得分: 2

prePersist和其他@createTimeStamp钩子在您通过使用JPA或本机Hibernate方法从应用程序内部进行插入时起作用。如果您只是从应用程序上下文之外运行插入操作,Hibernate不会知道正在运行什么DML,因此钩子永远不会被调用。如果您希望即使在外部运行插入操作时,创建的时间戳也能自动填充,您需要添加表级别的DDL指令。
例如:ALTER TABLE mytable ALTER COLUMN datecreated SET DEFAULT now();

至于Hibernate的自动DDL能力,xml属性&lt;property name=&quot;hibernate.hbm2ddl.auto&quot;&gt;create&lt;/property&gt;会根据实体定义生成DDL,但不会生成DML。因此,您还可以在相关实体的列定义中嵌入DEFAULT时间戳值,如下所示或类似方式:

@Column(name=&quot;datecreated&quot;, columnDefinition=&quot;TIMESTAMP DEFAULT CURRENT_TIMESTAMP&quot;)

这将确保在创建表时,使用Hibernate设置的自动DDL属性应用定义。

希望这能澄清您的疑问。

英文:

The prePersist and other @createTimeStamp hooks works if you are making inserts from within the application by using the JPA or native hibernate methods. If you simply run inserts from outside your application context, there is no way hibernate would come to know what DMLs are running and hence the hooks will never be called. If you want that even from outside when you run the inserts, the timestamp for create should auto populate, you would need to add table level DDL instructions.
Eg: ALTER TABLE mytable ALTER COLUMN datecreated SET DEFAULT now();

Now as to auto DDL ability of hibernate, the xml property &lt;property name=&quot;hibernate.hbm2ddl.auto&quot;&gt;create&lt;/property&gt; generates DDL from entity definitions but not DMLs. So, you can also embed the DEFAULT timestamp value in column definition of the concerned entity as so or similar:

@Column(name=&quot;datecreated&quot;, columnDefinition=&quot;TIMESTAMP DEFAULT CURRENT_TIMESTAMP&quot;)

This will ensure that when the table is created, the definition is applied using the auto DDL property of hibernate settings.

Hope this clarifies

答案2

得分: 0

在您的图像模型类中,使用时间戳

@CreationTimestamp
@Column
private Timestamp timestamp;
英文:

In your image model class, use timestamp

@CreationTimestamp
@Column
private Timestamp timestamp;

huangapple
  • 本文由 发表于 2020年9月21日 10:44:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/63985536.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定