1. 程式人生 > >Hibernate 列舉型別@Enumerated(EnumType.STRING)的應用

Hibernate 列舉型別@Enumerated(EnumType.STRING)的應用

目的:希望通過列舉,以String形式與資料庫對應欄位傳遞,遇到了一些報錯,在網上的解決方法大多都解決不了


 

案發現場(一開始的寫法):

報錯:,查詢的時候資料庫的值識別不了,沒法賦值給實體類

程式碼:

    /**
     * 裝置標識.equipment
     */
    @Getter
    @Setter
    @Size(max = 128)
    @NotNull
    @Comment("裝置標識,")
    @Column(name = "equipment" , length = 128 , nullable = false)
    @Enumerated(EnumType.STRING)
    private EquipmentType equipment;
    /**
     * 列舉:伺服器型別
     *  */
    public enum EquipmentType {
        /** 0-切片伺服器 */
        SECTIONS(0, "切片伺服器"),
        /** 1-其他伺服器 */
        OTHER(1, "其他伺服器");

        /** 值 */
        private Integer value;
        private String label;

        /** 取值 */
        public String getLabel() { return label; }

        public Integer getValue() { return this.value; }

        EquipmentType(Integer value, String label) {
            this.value = value;
            this.label = label;
        }
    }

分析:

誤認為使用了@Enumerated(EnumType.STRING)註解,就相當於分配上面的 label(列舉第二個引數)與資料庫互動,在這折騰了好久,其實並非這樣


EnumType原始碼如下:

列舉型別預設是按他的索引跟資料庫關聯,也可以指定說他的 value(列舉第一個引數),即第一種ORDINAL(索引)。

第二種是以列舉的value值跟資料庫關聯,如上面的實體類的SECTION、OTHER

總結:

也就要麼存的是它的索引,即ordinal,要麼是value值,如SECTION、OTHER


於是列舉程式碼改成:

    /**
     * 列舉:伺服器型別
     *  */
    public enum EquipmentType {
        /** 0-切片伺服器 */
        切片伺服器(0, "切片伺服器"),
        /** 1-其他伺服器 */
        其他伺服器(1, "其他伺服器");

        /** 值 */
        private Integer value;
        private String label;

        /** 取值 */
        public String getLabel() { return label; }

        public Integer getValue() { return this.value; }

        EquipmentType(Integer value, String label) {
            this.value = value;
            this.label = label;
        }
    }

這樣實體類和資料庫關聯起來

 


遇到的報錯: 

解決:去掉size的限定 

    /**
     * 裝置標識.equipment
     */
    @Getter
    @Setter
    @NotNull
    @Comment("裝置標識,")
    @Column(name = "equipment" , nullable = false)
    @Enumerated(EnumType.STRING)
    private EquipmentType equipment;