gpt4 book ai didi

java - Spring-Data-Jpa AuditingEntityListener createdDate 在保存现有实体时更新

转载 作者:行者123 更新时间:2023-11-29 06:31:10 25 4
gpt4 key购买 nike

我有以下 JPA 实体:

@EntityListeners(AuditingEntityListener.class)
@Entity
public class EntityWithAuditingDates {

@Id
@GeneratedValue
private Long id;

@Temporal(TemporalType.TIMESTAMP)
@CreatedDate
private Date createdDate;

@Temporal(TemporalType.TIMESTAMP)
@LastModifiedDate
private Date lastModified;

private String property;

// getters and setters omitted.
}

以及以下 CrudRepository:

@Service
public interface EntityWithAuditingDatesRepository extends CrudRepository<EntityWithAuditingDates, Long> {

}

以及以下测试:

@SpringApplicationConfiguration(classes = FooApp.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class AuditingEntityListenerTest {

@Autowired
private EntityWithAuditingDatesRepository entityWithAuditingDatesRepository;

@Test
public void test() {
EntityWithAuditingDates entityWithAuditingDates = new EntityWithAuditingDates();
entityWithAuditingDates.setProperty("foo");
assertNull(entityWithAuditingDates.getCreatedDate());
assertNull(entityWithAuditingDates.getLastModified());
entityWithAuditingDatesRepository.save(entityWithAuditingDates);
assertNotNull(entityWithAuditingDates.getCreatedDate());
assertNotNull(entityWithAuditingDates.getLastModified());
assertEquals(entityWithAuditingDates.getLastModified(), entityWithAuditingDates.getCreatedDate());
entityWithAuditingDates.setProperty("foooo");
entityWithAuditingDatesRepository.save(entityWithAuditingDates);
assertNotEquals(entityWithAuditingDates.getCreatedDate(), entityWithAuditingDates.getLastModified());
}
}

最后一个条件不成立。更新实体后 createdDate 和 lastModifiedDate 不应该不同吗?

谢谢!

最佳答案

我遇到了同样的问题,但现在找到了解决方法。在@Column 上,我设置了 updatable=false 以在更新时排除 create* 字段。

  @CreatedBy
@NotNull
@Column(name = "created_by", nullable = false, length = 50, updatable = false)
private String createdBy;

@CreatedDate
@NotNull
@Column(name = "created_date", nullable = false, updatable = false)
private ZonedDateTime createdDate = ZonedDateTime.now();

@LastModifiedBy
@Column(name = "last_modified_by", length = 50)
private String lastModifiedBy;

@LastModifiedDate
@Column(name = "last_modified_date")
private ZonedDateTime lastModifiedDate = ZonedDateTime.now();

关于java - Spring-Data-Jpa AuditingEntityListener createdDate 在保存现有实体时更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33500860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com