Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 0a110d960c4c90b41d6eee273ee9985a81751b75 (plain) (blame)
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
 * <copyright>
 *
 * Copyright (c) 2005, 2006, 2007, 2008 Springsite BV (The Netherlands) and others
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Martin Taal
 * </copyright>
 *
 * $Id: CDOENumIntegerType.java,v 1.1 2009-03-19 17:20:14 mtaal Exp $
 */

package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;

import org.eclipse.emf.common.util.Enumerator;
import org.hibernate.HibernateException;

/**
 * Implements the EMF UserType for an Enum in a dynamic model, for an integer field.
 * 
 * @author <a href="mailto:mtaal@elver.org">Martin Taal</a>
 * @version $Revision: 1.1 $ $Date: 2009-03-19 17:20:14 $
 */

public class CDOENumIntegerType extends CDOENumStringType {

	/** The sql types used for enums */
	private static final int[] SQL_TYPES = new int[] { Types.INTEGER };

	/** Hashmap with string to enum mappings */
	private final HashMap<Integer, Enumerator> localCache = new HashMap<Integer, Enumerator>();

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.hibernate.usertype.UserType#nullSafeGet(java.sql.ResultSet, java.lang.String[],
	 *      java.lang.Object)
	 */
	@Override
	public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
		final int value = rs.getInt(names[0]);
		if (rs.wasNull()) {
			return null;
		}

		Integer objValue = new Integer(value);
		Enumerator enumValue = localCache.get(objValue);
		if (enumValue != null) {
			return enumValue;
		}

		enumValue = enumInstance.getEEnumLiteral(objValue.intValue());
		localCache.put(objValue, enumValue);
		return enumValue;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.hibernate.usertype.UserType#nullSafeSet(java.sql.PreparedStatement,
	 *      java.lang.Object, int)
	 */
	@Override
	public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
		if (value == null) {
			st.setNull(index, Types.INTEGER);
		} else {
			st.setInt(index, ((Enumerator) value).getValue());
		}
	}

	/** An enum is stored in one varchar */
	@Override
	public int[] sqlTypes() {
		return SQL_TYPES;
	}
}

Back to the top