自动将日期存储到数据库中

时间:2019-08-19 09:03:30

标签: java hibernate spring-boot

我想将文章存储在我的表中,希望自动生成发布日期并将其存储在数据库中。 每当我添加文章时,文章表中的列publishedDate就会显示NULL。我想自动插入日期,该怎么办? 我的实体类和JSP文件中包含以下代码

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@page import="java.util.Date" %>
<jsp:useBean id="now" class="java.util.Date" />

<c:url value="/admin/article/save" var="url"></c:url>
            <form:form class="form-horizontal" action="${url}" modelAttribute="article"
                method="POST" enctype="multipart/form-data" style="margin-top:5rem;" >
                <fieldset>

                <form:hidden path="articleViews" value="${article.articleViews}" />
                <form:hidden path="publishedDate" id="publishedDate" value="${now}" />
                <form:hidden path="articleId" value="${article.articleId}" />
import java.io.Serializable;
import java.util.Comparator;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import javax.persistence.Table;
import javax.persistence.Transient;

import org.hibernate.annotations.Generated;
import org.hibernate.annotations.GenerationTime;
import org.springframework.web.multipart.MultipartFile;

@Entity
@Table
public class Article implements Serializable,Comparator<Article>{


    /**
     * 
     */
    private static final long serialVersionUID = -4756552789390263788L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long articleId;
    private String articleHeading;
    @Column(columnDefinition = "TEXT")

    private String articleIntroduction;
    @Column(columnDefinition = "TEXT")

    private String articleDescription;
    @Column(columnDefinition = "TEXT")

    private String articleSummary;
    @Transient
    private MultipartFile aImage;

   private String articleCategory;

   @Generated(GenerationTime.ALWAYS)
  @Column(name="publishedDate" ,columnDefinition = "TIMESTAMP")
     private Date publishedDate ;


    public long getArticleViews() {
        return articleViews;
    }
    public void setArticleViews(long articleViews) {
        this.articleViews = articleViews;
    }

        @Column( nullable = false, columnDefinition = "bigint(20) default 0")
   private long articleViews = 0;

1 个答案:

答案 0 :(得分:0)

复制this post,使用//same code as in man.html @PrePersist
或者也可以结合@PreUpdate@CreationTimestamp