Do NOT populate @UpdateTimestamp field when entity gets created

#1

Is there a way to configure an @UpdateTimestamp field so it won’t get populated when the entity gets created but only when the entity gets updated?

Here is what I’m doing in this addUser operation,

@Entity
@Table(schema = "alpha", name = "user_profile")
public class User {

	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_id_sequence_generator")
	@SequenceGenerator(name = "user_id_sequence_generator", schema = "alpha", allocationSize = 1, sequenceName = "user_id_seq")
	private Integer id;

	private String login;

	private String password;

	@CreationTimestamp
	private LocalDateTime created;

	@UpdateTimestamp
	private LocalDateTime modified;
		User newUser = new User();
		newUser.setLogin(addUserInput.getLogin());
		newUser.setPassword(md5DigestAsHex(addUserInput.getPassword().getBytes()));

		userRepository.save(newUser);
		entityManager.flush();

		UserOutputTO addUserOutput = new UserOutputTO();
		addUserOutput.setId(newUser.getId());
		addUserOutput.setLogin(addUserInput.getLogin());
		addUserOutput.setCreated(newUser.getCreated());
		addUserOutput.setModified(newUser.getModified());

		return addUserOutput;
#2

Does anyone have an idea?

#3

The reason that happens is because Hibernate only supports 3 modes of GenerationTiming

  1. NEVER - No value is generated at insert or update.
  2. INSERT - Value is only generated at insert.
  3. ALWAYS - Value is generated at insert and update.

For the @UpdateTimetamp annotation, it uses the ALWAYS mode, which is why you are seeing the behavior you do where it gets set both on insert and update.

One idea might be to explicitly mark the column as not-insertable and see whether that is sufficient enough to avoid the column being included in the insert statements.

@Column(insertable=false)
@UpdateTimestamp
private LocalDateTime modified;