【问题标题】:How to check that invalid data in database for enum如何检查数据库中的无效数据以获取枚举
【发布时间】:2016-03-11 13:27:58
【问题描述】:

我有以下字段声明:

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

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

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

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

现在我的 dao 方法抛出

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

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

【问题讨论】:

    标签: java hibernate jpa enums exception-handling


    【解决方案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);  
            }      
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-21
      • 2022-08-18
      • 1970-01-01
      • 2018-12-24
      • 1970-01-01
      相关资源
      最近更新 更多