枚举 Java 未保存为带有枚举注释的字符串

Enum Java Not saved as Strings with Enumerated Annotation

我无法创建要在 MySQL 数据库中保存为字符串的枚举。 我有一个 MySQL table 字段:

status varchar(50)

枚举

public enum Status {OPEN, CLOSED, CANCELLED, DONE}

实体

@Column(name="status", nullable=false)
private Status status;

@Enumerated(EnumType.STRING)
public Status getStatus() {return status;}

当我启动我的应用程序时,在获取数据时出现以下错误: SQLException:getInt() 的无效值'OPEN'

我也无法创建实体,出现 SQLGrammarError。它试图用 status=OPEN 而不是 status='OPEN'.

来保存对象

我遵循了文档 JavaDoc Persistence Enum 并尝试了这个 tutorial Jpa and Enums

通过在属性状态上添加@Enumerated(EnumType.STRING)。抓取错误不存在,但我创建实体时仍然有同样的错误。

错误日志

[DEBUG] com.vallois.valcrm.web.rest.BusinessResource - REST request to save         Business : Business{id=null, name='test', description='okokok',     createUpdateInfo=CreateUpdateInfo{createdUsername='user', updatedUsername='null',  createdDate=Thu May 21 16:04:54 CEST 2015, updatedDate=null}, status=CLOSED,  lock=PUBLIC}
Hibernate: insert into BUSINESS (created_date, created_name, updated_date, u pdated_name, description, lock, name, status, user_id) values (?, ?, ?, ?, ?, ?,    ?, ?, ?)
[WARN] org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 1064, SQLState: 42000
[ERROR] org.hibernate.engine.jdbc.spi.SqlExceptionHelper - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'lock, name, status, user_id) values ('2015-05-21 16:04:54', 'user', null, null, ' at line 1

@Enumerated移动到字段

@Column(name="status", nullable=false)
@Enumerated(EnumType.STRING)
private Status status;

编辑

您遇到的异常与枚举无关。 lock 是 MySQL 中的 reserved word,您必须将其名称更改为其他名称。

JPA 允许在字段或属性上进行注释,其中 @Id 的位置指定考虑两者中的哪一个。

所以在这种情况下,我猜你将不得不 @Enumerated(EnumType.STRING) 移动到该字段。