I am using MySQL database with Hibernate and there are certain Enum fields that allow NULL or empty values. It is all fine until a query is made and Hibernate tries to map the empty value on the Enum defined. I am unable to define a value in Enum that would work, because Enum does allow white-spaces.
Enum class:
private enum ObjType {
itemA,
itemB,
NULL
}
It takes NULL as a member but that does not help. I am new to EE Java, and would appreciate any help. Thanks
you can add a unknown or default or invalid value to your enum which will be mapped in case if it is null or empty space
package com.test;
import java.util.HashMap;
public class Brand{
private static HashMap<String,BrandName> map = new HashMap<String,BrandName>();
public enum BrandName {
HERO("hero"),HONDA("honda"),UNKNOWN("default");
private String value = null;
private BrandName(String value){
this.value = value;
addToMap();
}
private void addToMap(){
map.put(this.value, this);
}
@Override
public String toString(){
return this.value;
}
public static BrandName fromValue(String value){
return map.get(value) != null ? map.get(value) : map.get("default");
}
}
}
Using fromValue method you can get enum object from value.
using toString method you can get value of an enum object.
map will contain value to enum object mapping. If the value like null or empty space does not exist in map, the map will return null and in that case the method fromValue will return UNKNOWN enum object.
System.out.println(Brand.BrandName.HERO.toString());
System.out.println(Brand.BrandName.fromValue("").toString());
System.out.println(Brand.BrandName.fromValue(null).toString());
System.out.println(Brand.BrandName.fromValue("honda").toString());
You could use a default value to set the column to the NULL enum field in your entity.
@Enumerated(EnumType.STRING)
@Column(name="obj_type", columnDefinition="char(20) default 'NULL'")
ObjType objType;
and update existing rows.
update table set obj_type='NULL' where obj_type IS NULL
btw I would call the enum fields UNKNOWN because it could be confused with DB NULL-value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With