我正在尝试创建一个像这样的实体:
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;
}
}
我有它对应的存储库:
public interface EntityRepository extends JpaRepository<Entity, Entity.EntityId> {
}
但是执行
EntityRepository#findAll
会抛出以下错误:
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"
我还创建了相应的
AttributeConverter<Entity.EntityId, String>
,但我不知道还能做什么...仅供参考,如果我删除Entity.EntityId#id
并使用@Enumerated(STRING)
,它可以完美工作,但我需要该属性...
更新:
需要澄清的是,表的 id 是一个字符串,因此不可能使用枚举的序数。此外,不可能使用枚举的名称,因为表中填充有
a
、b
、c
和 d
;不是 A
、B
、C
或 D
。
不能使用枚举的 id 作为主键。这是不可能的。
您唯一能做的就是使用枚举字符串值。
@Id
@Enumerated(EnumType.STRING)
private EntityId id;
问题在于枚举是单例且不可变的值。因此,为了使您的示例正常工作,需要有一个枚举的设置器。
我尝试像这样使用枚举作为主键。
public class Entity {
@Id
@Column(name = "id")
@Enumerated(EnumType.STRING)
private EntityId id;
}
public enum EntityId {
A("a"),
B("b"),
C("c"),
D("d");
@Getter
private final String id;
}