Spring Boot 插入数据自动生成日期字段

在Spring Boot环境下,使用Spring Data 插入数据时,对某个字段自动生成当前日期时间。

1. 在Entity类中加入@EntityListeners注解,在需要自动生成日期的字段上加上@CreatedDate

@Entity
@Table
@EntityListeners(AuditingEntityListener.class)
public class Answer implements Serializable {
	private static final long serialVersionUID = 1L;
	
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(unique=true, nullable=false, insertable=true, updatable=true, length=32)
	private Long id;
	@Column
	private Long respondentId;
	@Column
	private Long seasonId;
	@Column
	private Long questionId;
	@Column
	private Integer optionAnswer;
	@Column
	private String textAnswer;
	
	@CreatedDate
	@Column
	private Date createdDate;

2. 在Application类加上@EnableJpaAuditing注解

@SpringBootApplication
@EnableJpaAuditing
public class QuestionnaireApplication {

	public static void main(String[] args) {
		SpringApplication.run(QuestionnaireApplication.class, args);
	}
}
3. 写上Repository接口后,就能直接保存了。
public interface AnswerRepository extends JpaRepository<Answer, Long> {

}
answerRepository.saveAll(answers);




阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页