如何实现文章表publishedDate字段自动生成并写入数据库?
Hey there! Let's dig into why your publishedDate is ending up as NULL when you create a new article, and fix it for good.
First, let's break down the root issues with your current setup:
- The JSP's hidden field for
publishedDatemight not bind correctly to theDatetype in your entity (since${now}outputs a human-readable string that Spring can fail to parse into a validDateobject). - The
@Generated(GenerationTime.ALWAYS)annotation could conflict with your attempts to set the date, as it tells Hibernate to expect the database to generate this value—but your database column doesn’t have a default configured to do that.
Here are three reliable solutions, ordered by how robust and low-maintenance they are:
1. Use JPA's @PrePersist Annotation (Most Recommended)
This method lets you set the date directly in the entity right before it’s saved to the database, so you don’t rely on front-end input or database configurations.
Update your Article entity class by adding a @PrePersist method:
@Entity @Table public class Article implements Serializable, Comparator<Article>{ // ... your existing fields and methods @Column(name="publishedDate", columnDefinition = "TIMESTAMP") private Date publishedDate ; // Auto-set the date when the article is first saved @PrePersist protected void onCreate() { // Only set the date if it's null (avoids overwriting it during updates) if (publishedDate == null) { publishedDate = new Date(); } } // ... your getters and setters }
This method runs automatically when you save a new article, ensuring publishedDate is always populated with the current time. It leaves existing dates untouched when you update the article later.
2. Let the Database Auto-Generate the Date
If you prefer to handle this at the database level, modify your entity’s publishedDate column to use a database default value:
@Entity @Table public class Article implements Serializable, Comparator<Article>{ // ... your existing fields and methods // Remove the @Generated annotation, and add a DEFAULT rule to the column @Column(name="publishedDate", columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP") private Date publishedDate ; // ... your getters and setters }
This tells your database (like MySQL) to automatically insert the current timestamp whenever a new row is added and publishedDate isn’t provided explicitly.
3. Manually Set the Date in Your Controller
If you want explicit control in your business logic, set the date in your save method before persisting the article:
@PostMapping("/admin/article/save") public String saveArticle(@ModelAttribute Article article) { // Check if publishedDate is null (only applies to new articles) if (article.getPublishedDate() == null) { article.setPublishedDate(new Date()); } // Save the article using your repository articleRepository.save(article); return "redirect:/admin/articles"; }
This bypasses any front-end date binding issues entirely.
Bonus: Fixing JSP Date Binding (If You Want to Keep Using It)
If you still want to pass the date from the JSP, you need to format it correctly so Spring can parse it into a Date object:
- Add the JSTL fmt taglib to your JSP:
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
- Format the date into a parsable string:
<jsp:useBean id="now" class="java.util.Date" /> <fmt:formatDate value="${now}" pattern="yyyy-MM-dd HH:mm:ss" var="formattedNow" /> <form:hidden path="publishedDate" value="${formattedNow}" />
- Add
@DateTimeFormatto your entity’s field to tell Spring how to parse the string:
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name="publishedDate", columnDefinition = "TIMESTAMP") private Date publishedDate ;
Note: This method is less reliable because front-end values can be tampered with or formatted incorrectly.
内容的提问来源于stack exchange,提问作者Quail UriBI

