I've the following structure:
When I'm saving an order to database, it gets saved with createdDate and lastModifiedDate automatically populated. After save, when I fetch the same order from database, createdDate
and lastModifiedDate
are returned as NULL. Why ?
BaseEntity.java
@MappedSuperclass
@Getter
@Setter
public abstract class BaseEntity {
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
@Column(length = 36, nullable = false)
private UUID id;
@CreationTimestamp
@Column(name = "created_date", updatable = false)
private Timestamp createdDate;
@UpdateTimestamp
@Column(name = "last_modified_date")
private Timestamp lastModifiedDate;
OrderEntity.java
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
@Table(name = "order")
public class Order extends BaseEntity {
private String customer;
@Embedded
private Address shippingAddress;
Below is the test that fails:
@SpringBootTest
class OrderRepositoryTest {
@Autowired
private OrderRepository orderRepository;
@Test
@Transactional
@Rollback(value = false)
public void test_saveOrderHeader() {
final Order order = Order.builder()
.customer("first buyer")
.build();
final OrderHeader savedOrder = orderRepository.save(order);
final Optional<Order> fetchedOrder = orderRepository.findById(savedOrder.getId());
assertNotNull(fetchedOrder);
assertNotNull(fetchedOrder.get().getId());
assertNotNull(fetchedOrder.get().getCreatedDate()); //test fails here, getting NULL
assertNotNull(fetchedOrder.get().getLastModifiedDate()); //getting NULL
}
}
Here is what I found during debugging:
savedOrder (debugging test): Note that fetchedOrder looks exactly same. In saved order, timestamp can be null because order hasn't been saved completely to DB yet. But in fetchedOrder (after savedOrder), it shouldn't be NULL.
But the order gets saved with timestamp in database (see below):
So what is going wrong here?
the following also works (I guess adding Transactional was the issue):
@SpringBootTest
class OrderRepositoryTest {
@Autowired
private OrderRepository orderRepository;
@Test
public void test_saveOrderHeader() {
final Order order = Order.builder()
.customer("first buyer")
.build();
final OrderHeader savedOrder = orderRepository.save(order);
final Optional<Order> fetchedOrder = orderRepository.findById(savedOrder.getId());
assertNotNull(fetchedOrder);
assertNotNull(fetchedOrder.get().getId());
assertNotNull(fetchedOrder.get().getCreatedDate());
assertNotNull(fetchedOrder.get().getLastModifiedDate());
}
}