0

Given a table in a mySQL database looks like this with the following columns:

| id  | name | reference|
  • id is a big-int auto-generated when persisting
  • name is a varchar
  • reference is a varchar

I am currently using spring-boot with spring-jpa.

Is there a way when I am persisting this entity to have the reference column be auto-generated in a custom way only when it is null. For example:

INSERT INTO my_table(name,reference) VALUES('John', 'MREF-System-0940');

Will produce a result as follows

| id  | name | reference        |
| 1   | John | MREF-System-0940 |

But when I execute the following

INSERT INTO my_table(name) VALUES('John');

Will produce a result as follows (Where reference is based as 'REF-{name}-{sequence}' where sequence could be the id or a predefined persistent sequence)

| id  | name | reference  |
| 2   | John | REF-John-2 |

It should auto-generate the reference column reference when it detects that column is null when persisting the entity.

If possible could we append the generated id column at the end? If not, is there a feasible way of auto-generating a reference as such.

Meaning if we do

INSERT INTO my_table(name) VALUES('Bob');

It might produce a result as follows

| id  | name | reference   |
| 3   | Bob  | REF-Bob-001 |
2
  • Are you using SQL for generate column? Commented Nov 6, 2020 at 14:38
  • @RafaelPizao for the id yes I am using database to auto increment. For the reference I am open to using java or database. I prefer java based as I can configure in future without redeployment Commented Nov 6, 2020 at 14:50

1 Answer 1

1

To make JPA generate field value you should use myEntityRepository#save instead of the native modifying query.

@Entity
public class MyEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    String name;
    String reference;

    public MyEntity(String name) {
        this.name = name;
    }

    //getters, setters, toString, hashcode, equals

    @PostPersist
    public void setReferencePostPersist(){
        if(id != null) {
            reference = "REF-" + name + "-" + id;
        }
    }
}

then

@Autowired
MyEntityRepository repository;

public MyEntity saveNewMyEntity(String name) {
    MyEntity myEntity = new MyEntity(name);   
    return repository.save(myEntity);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this works perfectly. Just add a null check in the postPersist method and all good to go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.