Skip to content

Instantly share code, notes, and snippets.

@shawnjohnson
Created May 8, 2018 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shawnjohnson/d93804882cee20dc22759fdaf1ca0358 to your computer and use it in GitHub Desktop.
Save shawnjohnson/d93804882cee20dc22759fdaf1ca0358 to your computer and use it in GitHub Desktop.
StringEnum enum example
@Entity
@TypeDef(name = "string-enum", typeClass = StringEnumType.class)
public class Book {
@Id
private String bookId;
@Enumerated(EnumType.STRING)
@Type(type="string-enum")
private BookType bookType;
private String title;
}
public enum BookType implements StringEnum {
SCIENCE_FICTION("Science fiction"),
Drama("Drama"),
ACTION_ADVENTURE("Action and Adventure")
}
/**
* <p>Enumerations that override toString and provide a fromString method can
* implement this interface. Implementers can annotate the use of their type
* with StringEnumType class, allowing for more seamless conversion to and from
* a PostgreSQL Enum field type.</p>
*
* <p>Note: Implementing classes are expected to implement a static `fromString`
* method and override toString. Interfaces do not allow you to specify a static
* modifier.</p>
*
* <p>Recommended static `fromString` method. This assumes desired behavior of returning a 'default' value.</p>
*
* <pre>
* public static MyEnum fromString(String representation) {
* return Arrays.stream(values()).filter(value -> value.toString().equals(representation)).findFirst()
* .orElse(getDefault());
* }
* </pre>
*
*
*/
public interface StringEnum {
}
/**
* Provides a way to have a string read and written using Hibernate.
*
* NOTE: The PostgresEnumType does not work with Enums having a string value
*
*
*/
public class StringEnumType extends org.hibernate.type.EnumType {
private static final long serialVersionUID = -7372724879821833735L;
public void nullSafeSet(
PreparedStatement st,
Object value,
int index,
SessionImplementor session)
throws HibernateException, SQLException {
if (value == null) {
st.setNull(index, Types.OTHER);
} else {
st.setObject(index, value.toString(), Types.OTHER);
}
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner)
throws SQLException {
String representation = rs.getString(names[0]);
if (rs.wasNull()) {
return null;
}
for (Enum<?> value : returnedClass().getEnumConstants()) {
if (value instanceof StringEnum) {
StringEnum stringEnum = (StringEnum) value;
if (stringEnum.toString().equals(representation)) {
return value;
}
}
}
throw new IllegalStateException("Unknown " + returnedClass().getSimpleName() + " string");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment