Home > Software engineering >  Use an enum as ID in JPA
Use an enum as ID in JPA

Time:11-29

I'm trying to create an entity like this:

public class Entity {

    @Id
    @Column(name = "id")
    private EntityId id;

    @RequiredArgsConstructor
    public enum EntityId {

        A("a"),
        B("b"),
        C("c"),
        D("d");

        @Getter
        private final String id;

    }

}

And I have its corresponding repository:

public interface EntityRepository extends JpaRepository<Entity, Entity.EntityId> {
}

But executing EntityRepository#findAll throws the following:

org.springframework.dao.DataIntegrityViolationException: could not execute query; SQL [select entity0_.id as id_1_2_ from entity entity0_];

...

Caused by: org.hibernate.exception.DataException: could not execute query

...

Caused by: org.h2.jdbc.JdbcSQLDataException: Data conversion error converting "b" [22018-200]

...

Caused by: java.lang.NumberFormatException: For input string: "b"

I also created the corresponding AttributeConverter<Entity.EntityId, String>, but I don't know what else to do... FYI if I remove Entity.EntityId#id and use @Enumerated(STRING) it works perfectly, but I need that property...

UPDATE:

To clarify, the table's id is a string, so using enum's ordinal is not possible. Also, it is not possible to use enum's name since the table is populated with a, b, c and d; not A, B, C or D.

CodePudding user response:

You cannot use the id of the enum as the primary key. That's not possible.

The only thing you can do is to use the enum string value.

@Id
@Enumerated(EnumType.STRING)
private EntityId id;

The problem is that enums are singleton and immutable values. So to make your example work it would be necessary to have a setter the enum.

  • Related