如何在数据库中检查枚举的无效数据

时间:2016-03-11 13:27:58

标签: java hibernate jpa enums exception-handling

我有以下字段声明:

@Entity
@Table
public class ConnectionInformation implements Serializable {
    @Enumerated(EnumType.STRING)
    @Column
    private ConnectionType connectionType;
    ....
}

在数据库connectionType中,varchar字段用户可以在那里键入任何字符串。

如果用户在此字段输入错误,我需要记录特定错误。

当我从数据库中读取实体时,如何在java代码中检查它?

现在我的dao方法抛出

 Unknown name value [trololo] for enum class [package.ConnectionType] 
    .... 
    'org.springframework.dao.InvalidDataAccessApiUsageException' exception.

我担心我不能依赖异常类型。可以为另一个字段抛出异常。

1 个答案:

答案 0 :(得分:1)

我认为,如果您将connectionType映射为String类型

会更好
@Entity
@Table
public class ConnectionInformation implements Serializable {

    @Column
    private String connectionType;

    @Transient  
    public ConnectionType getConnectionTypeAsEnum() {
        return connectionType == null ? null : ConnectionType.valueOf(connectionType); 
    }

    public void assertConnectionType() {
        try {
            getConnectionTypeAsEnum();
        } catch(IllegalArgumentException ex) {
            throw new IllegalArgumentException(
                String.format("Invalid `connectionType`: %s", conectionType), ex);  
        }      
    }

}