Spring boot - save non-id field depending on id field while saving object

Viewed 909

I have an auto increment id field in spring boot class:

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

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

private String code;

This field will have 6 alphanumeric (upper or lower case does not matter).

Is it possible to save this field auto while a new object created for that class, with such a method?

Long.toString("id_field_value",36);

Actually, it gives:

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

So, when first object is created, id will be 1.

Any suggestion?

For example, when i save Person object,

the id will be 1 automatically with JPA - hibarnate.

And also i want another field to be saved automatically, which is depending on id field.

So, id is 1, that string code must be 1 also.

Should i do this after creating object ? Like:

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

2 Answers

You can try @PostPersist annotation. You will have an id in your entity as soon as it is persisted. Something like:

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

This works fine as long as EntityManager is used, the field code should also be persisted to the db.

When using Spring repositories it might be needed to perform extra save() (I do not have to, having just default config) after initial save but you should test this approach with your configuration.

(Spring repositories handle persistence context a bit different way compared to the JPA standard usage with EntityManager.)

It seems like the code column you want is just exactly the id column but with another encoding (base 36 rather than base 10).

You don't need to store it, nor use a persistence annotation for that :

  • For reading the code : on the entity, just add a getter method getCode() that compute it based on the id value.
  • For searching by code, just convert the code from base 36 to base 10, then search by id.
Related