Nick
Nick

Reputation: 771

Auto value generation for spring boot

I am a NodeJS backend Dev, started learning spring boot, I was just wandering if it's possible to generate a field value with existing values for different field.

let me clear my request. Let's suppose its my model,

import javax.persistence.*;
import java.util.Date;
import java.util.UUID;

@Entity
@Table(name = "tbl_user")
public class UserModel {

    @Id
    @GenericGenerator(name = "UUIDGenerator", strategy = "uuid2")
    @GeneratedValue(generator = "UUIDGenerator")
    @Column(name = "uuid", updatable = false, nullable = false)
    private UUID uuid;

    @Column(name = "userName", updatable = true, nullable = false)
    private String userName;

    @Column(name = "userNameToLower", updatable = true, nullable = false)
    private String userNameToLower;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserNameToLower() {
        return userNameToLower;
    }

    public void setUserNameToLower(String userNameToLower) {
        this.userNameToLower = userNameToLower;
    }
}

On basis of userName(will be taken from request body, can I generate userNameToLower at the time of pushing it to DB, without coding it explicitly on controller.

please let me know. It will be a great help.

Thanks in advance.

Upvotes: 1

Views: 999

Answers (2)

Waleed
Waleed

Reputation: 73

In hibernate, there is way. Try below:

@Column(name = "userName")
@ColumnTransformer(write = "LOWER(userName)")
private String userName;

Upvotes: 1

Michiel
Michiel

Reputation: 3410

You could make use of the @PrePersist and @PreUpdate annotations to set up methods that are invoked before an entity is saved or updated. Use @EntityListeners if you want to move the logic to a separate class.

@Entity
@Table(name = "tbl_user")
public class UserModel {
  // ...

  @PrePersist
  private void prePersist() {

    // simple example without null check, etc
    username = username.toLowerCase();
  }
}

Some examples:

Upvotes: 3

Related Questions