/
PostgreSQLEnumType.java
53 lines (44 loc) · 1.65 KB
/
PostgreSQLEnumType.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.vladmihalcea.hibernate.type.basic;
import com.vladmihalcea.hibernate.type.util.Configuration;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
/**
* Maps an {@link Enum} to a PostgreSQL ENUM column type.
* <p>
* For more details about how to use it, check out <a href="https://vladmihalcea.com/the-best-way-to-map-an-enum-type-with-jpa-and-hibernate/">this article</a> on <a href="https://vladmihalcea.com/">vladmihalcea.com</a>.
*
* @author Vlad Mihalcea
*/
public class PostgreSQLEnumType extends org.hibernate.type.EnumType {
public static final PostgreSQLEnumType INSTANCE = new PostgreSQLEnumType();
private final Configuration configuration;
/**
* Initialization constructor taking the default {@link Configuration} object.
*/
public PostgreSQLEnumType() {
this.configuration = Configuration.INSTANCE;
}
/**
* Initialization constructor taking the {@link Class} and {@link Configuration} objects.
*
* @param configuration custom {@link Configuration} object.
*/
public PostgreSQLEnumType(Configuration configuration) {
this.configuration = configuration;
}
public void nullSafeSet(
PreparedStatement st,
Object value,
int index,
SessionImplementor session)
throws HibernateException, SQLException {
st.setObject(index, value != null ? ((Enum) value).name() : null, Types.OTHER);
}
@Override
public int[] sqlTypes() {
return new int[]{Types.VARCHAR};
}
}