JPA tips&tricks

Mapping enum to string column

// Define enum
    public enum EventSource {
        device, cloud
    }

// Create user type
public static class EventSourceEnumType implements UserType<EventSource> {
        @Override
        public int getSqlType() {
            return SqlTypes.OTHER;
        }

        @Override
        public Class<EventSource> returnedClass() {
            return EventSource.class;
        }

        @Override
        public boolean equals(EventSource x, EventSource y) {
            return Objects.equals(x, y);
        }

        @Override
        public int hashCode(EventSource x) {
            return Objects.hashCode(x);
        }

        @Override
        public EventSource nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException {
            return EventSource.valueOf(rs.getString(position));
        }

        @Override
        public void nullSafeSet(PreparedStatement st, EventSource value, int index, SharedSessionContractImplementor session) throws SQLException {
            st.setObject(index, value.name(), SqlTypes.OTHER);
        }

        @Override
        public EventSource deepCopy(EventSource value) {
            return value;
        }

        @Override
        public boolean isMutable() {
            return false;
        }

        @Override
        public Serializable disassemble(EventSource value) {
            return value;
        }

        @Override
        public EventSource assemble(Serializable cached, Object owner) {
            return (EventSource) cached;
        }
    }



// On Entity add property with enum
    @Column(name = "event_source")
    @Type(value = EventSourceEnumType.class, parameters = {
            @org.hibernate.annotations.Parameter(name = "type", value = "1111"),
            @org.hibernate.annotations.Parameter(name = "useNamed", value = "true")
    })
    EventSource eventSource;

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *