Home > Back-end >  JPA: Validate fetched field against an Enum
JPA: Validate fetched field against an Enum

Time:07-21

I have an entity like so:


@Entity
@Table(name = "MyTable", schema = "test")
@Getter @Setter
public class PurgeSystemsEntity {

    @Id
    @Column(name = "id", nullable = false)
    private int id;

    @Column(name = "system_name", nullable = false, length = 255)
    private String systemName;
.
.
}

How do I validate that the string obtained from DB (like when doing a .findAll()) in systemName field is one of the possible options defined in the Enum System :

    public static enum System {
        PROD, DEV, QA;
    }

So, If a row is fetched with systemName value being 'STAGING', it should throw an exception immediately.

Is there some elegant way to do this?

CodePudding user response:

Set the field type to the enum.

@Column(name = "system_name", nullable = false, length = 255)
@Enumerated(EnumType.STRING)
private System systemName;

This will cause an error if you encounter a value not defined in the enum.

You also have to set EnumType.STRING explicitly, as it defaults to EnumType.ORDINAL which would correspond to the enum ordinal value instead of the name

CodePudding user response:

You can write your own method in ENUM

Something like this

public static MyEnum fromValue(String value) {
    for (MyEnum b : MyEnum.values()) {
      if (b.value.equals(value)) {
        return b;
      }
    }
    throw new IllegalArgumentException("Unexpected value '"   value   "'");
  }

Alternatively, if your Enum is part of your class, I think , Java should automatically handle and throw IllegalArgumentException if the value cannot be mapped !

  • Related