Project

General

Profile

1
package eu.dnetlib.openaire.common;
2

    
3
import java.io.Serializable;
4
import java.sql.*;
5

    
6
import org.hibernate.HibernateException;
7
import org.hibernate.engine.spi.SharedSessionContractImplementor;
8
import org.hibernate.usertype.UserType;
9

    
10
/**
11
 * Created by claudio on 05/07/2017.
12
 */
13
public class GenericArrayUserType<T extends Serializable> implements UserType {
14

    
15
	protected static final int[] SQL_TYPES = { Types.ARRAY };
16

    
17
	private  Class<T> typeParameterClass;
18

    
19
	@Override
20
	public Object assemble(Serializable cached, Object owner) throws HibernateException {
21
		return this.deepCopy(cached);
22
	}
23

    
24
	@Override
25
	public Object deepCopy(Object value) throws HibernateException {
26
		return value;
27
	}
28

    
29
	@SuppressWarnings("unchecked")
30
	@Override
31
	public Serializable disassemble(Object value) throws HibernateException {
32
		return (T) this.deepCopy(value);
33
	}
34

    
35
	@Override
36
	public boolean equals(Object x, Object y) throws HibernateException {
37

    
38
		if (x == null) {
39
			return y == null;
40
		}
41
		return x.equals(y);
42
	}
43

    
44
	@Override
45
	public int hashCode(Object x) throws HibernateException {
46
		return x.hashCode();
47
	}
48

    
49
	@Override
50
	public Object nullSafeGet(final ResultSet resultSet,
51
			final String[] names,
52
			final SharedSessionContractImplementor sharedSessionContractImplementor,
53
			final Object o)
54
			throws HibernateException, SQLException {
55
		if (resultSet.wasNull()) {
56
			return null;
57
		}
58
		if (resultSet.getArray(names[0]) == null) {
59
			return new Integer[0];
60
		}
61

    
62
		Array array = resultSet.getArray(names[0]);
63
		@SuppressWarnings("unchecked")
64
		T javaArray = (T) array.getArray();
65
		return javaArray;
66
	}
67

    
68
	@Override
69
	public void nullSafeSet(final PreparedStatement statement,
70
			final Object value,
71
			final int index,
72
			final SharedSessionContractImplementor session)
73
			throws HibernateException, SQLException {
74
		Connection connection = statement.getConnection();
75
		if (value == null) {
76
			statement.setNull(index, SQL_TYPES[0]);
77
		} else {
78
			@SuppressWarnings("unchecked")
79
			T castObject = (T) value;
80
			Array array = connection.createArrayOf("integer", (Object[]) castObject);
81
			statement.setArray(index, array);
82
		}
83
	}
84

    
85
	@Override
86
	public boolean isMutable() {
87
		return true;
88
	}
89

    
90
	@Override
91
	public Object replace(Object original, Object target, Object owner) throws HibernateException {
92
		return original;
93
	}
94

    
95
	@Override
96
	public Class<T> returnedClass() {
97
		return typeParameterClass;
98
	}
99

    
100
	@Override
101
	public int[] sqlTypes() {
102
		return new int[] { Types.ARRAY };
103
	}
104

    
105

    
106
}
(4-4/9)