1 package com.vladmihalcea.hibernate.type.basic;
2
3 import com.vladmihalcea.hibernate.type.ImmutableType;
4 import org.hibernate.HibernateException;
5 import org.hibernate.MappingException;
6 import org.hibernate.engine.jdbc.Size;
7 import org.hibernate.engine.spi.Mapping;
8 import org.hibernate.engine.spi.SessionFactoryImplementor;
9 import org.hibernate.engine.spi.SharedSessionContractImplementor;
10 import org.hibernate.type.ForeignKeyDirection;
11 import org.hibernate.type.Type;
12
13 import java.io.Serializable;
14 import java.sql.PreparedStatement;
15 import java.sql.ResultSet;
16 import java.sql.SQLException;
17 import java.sql.Types;
18 import java.util.Map;
19
20 /**
21  * Maps an {@link Character} to a nullable CHAR column type.
22  * <p>
23  * For more details about how to use it, check out <a href="https://vladmihalcea.com/how-to-implement-a-custom-basic-type-using-hibernate-usertype/">this article</a> on <a href="https://vladmihalcea.com/">vladmihalcea.com</a>.
24  *
25  * @author Vlad Mihalcea
26  */

27 public class NullableCharacterType extends ImmutableType<Character> {
28
29     public static final NullableCharacterType INSTANCE = new NullableCharacterType();
30
31     public NullableCharacterType() {
32         super(Character.class);
33     }
34
35     @Override
36     public int[] sqlTypes() {
37         return new int[]{Types.CHAR};
38     }
39
40     @Override
41     public Character get(ResultSet rs, String[] names,
42                          SharedSessionContractImplementor session, Object owner) throws SQLException {
43         String value = rs.getString(names[0]);
44         return (value != null && value.length() > 0) ? value.charAt(0) : null;
45     }
46
47     @Override
48     public void set(PreparedStatement st, Character value, int index,
49                     SharedSessionContractImplementor session) throws SQLException {
50         if (value == null) {
51             st.setNull(index, Types.CHAR);
52         } else {
53             st.setString(index, String.valueOf(value));
54         }
55     }
56 }