Project

General

Profile

1
package eu.dnetlib.openaire.exporter.model;
2

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

    
6
import org.hibernate.HibernateException;
7
import org.hibernate.engine.spi.SessionImplementor;
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 boolean isMutable() {
51
		return true;
52
	}
53

    
54
	@Override
55
	public Object nullSafeGet(ResultSet resultSet, String[] names, SessionImplementor session, Object owner)
56
			throws HibernateException, SQLException {
57
		if (resultSet.wasNull()) {
58
			return null;
59
		}
60
		if (resultSet.getArray(names[0]) == null) {
61
			return new Integer[0];
62
		}
63

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

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

    
84
	@Override
85
	public Object replace(Object original, Object target, Object owner) throws HibernateException {
86
		return original;
87
	}
88

    
89
	@Override
90
	public Class<T> returnedClass() {
91
		return typeParameterClass;
92
	}
93

    
94
	@Override
95
	public int[] sqlTypes() {
96
		return new int[] { Types.ARRAY };
97
	}
98

    
99

    
100
}
(2-2/2)