Issue
I have the following entity, which reflects some kind of background task and gonna be updated. I thought using the JPA auditing would be useful so I included it like this:
@Entity
@RequiredArgsConstructor
@Getter
@Setter
@Table(name = "FOO")
public class FooJob{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID", unique = true, nullable = false)
private long id;
@LastModifiedDate
@Column(name = "FINISHED", nullable = false)
private LocalDateTime finished;
...
}
@Repository
public interface FooJobRepository
extends JpaRepository<FooJob, Long>,
JpaSpecificationExecutor<FooJob> {}
and I have enabled the @EnableJpaAuditing
on the spring-boot application
spring version:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.0</version>
<relativePath />
</parent>
But when running the code like this:
@Service
@Transactional
/*package*/ class FooJobService{
public void run() {
FooJob job = createJob();
....
}
private FooJob createJob(){
FooJob job = new FooJob();
job.setSomeValue("123");
//Do not set "finished" date here
repo.saveAndFlush(job); //THIS LINE THROWS EXCEPTION
}
}
Ill get the following exception:
org.springframework.dao.DataIntegrityViolationException: not-null property references a null or transient value : my.package.entity.FooJob.finished; nested exception is org.hibernate.PropertyValueException: not-null property references a null or transient value : my.package.entity.FooJob.finished
Why does this not work?
Solution
Add this to Entity if you only update finished date:
@EntityListeners(AuditingEntityListener.class)
Answered By - Miguel Angel
Answer Checked By - Cary Denson (JavaFixing Admin)