Java – Spring boot – saves non-id fields based on id fields when saving objects

Spring boot – saves non-id fields based on id fields when saving objects… here is a solution to the problem.

Spring boot – saves non-id fields based on id fields when saving objects

I have an auto-incrementing id field in the Spring Boot class:

private long id //or it can be int, does not matter

I have another field in the same class, which must be unique and alphanumeric:

private String code;

This field will have 6 alphanumeric (uppercase or lowercase does not matter).

Is it possible to use this approach to automatically save the field when a new object is created for the class?

Long.toString("id_field_value",36);

Actually, it gives:

0 -> 0
1 -> 1
10 -> A

Therefore, when the first object is created, the id will be 1.

Any suggestions?

For example, when I save the Person object

With JPA – hibarnate, the id will automatically be 1.

I also want another field to be saved automatically, depending on the id field.

So, if the id is 1, then the string code must also be 1.

Should I do this after creating the object? Like :

Person person = personRepository.save(person3);
person.setCode(person.getId().toString); // or other functions

Solution

You can try using @PostPersist annotations. Once persisted, you will have an ID in your entity. Something like this:

@PostPersist
private void postPersist() {
    this.setCode( generateMyCode( getId() ) );
}

As long as EntityManager works fine, the field code should also be saved to the database.

When using a Spring repository, you may need to do additional save() after the initial save (I don’t have to do this, only the default configuration), but you should test this method with your configuration.

(Spring repositories handle persistence contexts slightly differently than JPA standard usage using EntityManager.) )

Related Problems and Solutions