1 package org
.codehaus
.groovy
.grails
.orm
.hibernate
3 import javax
.sql
.DataSource
6 * @author Graeme Rocher
8 class UserTypeMappingTests
extends AbstractGrailsHibernateTests
{
10 protected void onSetUp() {
12 import org.hibernate.type.*
13 class UserTypeMappingTest
23 active (column: 'active
', type: YesNoType)
31 import org.hibernate.usertype.UserType
33 import org.hibernate.type.Type
34 import java.sql.PreparedStatement
35 import java.sql.ResultSet
36 import java.sql.SQLException
37 import org.hibernate.Hibernate
38 import org.hibernate.HibernateException
41 class WeightUserType implements UserType {
43 private static final int[] SQL_TYPES = [ Types.INTEGER ]
44 public int[] sqlTypes() {
48 public Class returnedClass() {
52 public boolean equals(Object x, Object y) throws HibernateException {
55 } else if (x == null || y == null) {
62 public int hashCode(Object x) throws HibernateException {
66 public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) throws HibernateException, SQLException {
68 int pounds = resultSet.getInt(names[0])
69 if (!resultSet.wasNull()) {
70 result = new Weight(pounds)
75 public void nullSafeSet(PreparedStatement statement, Object value, int index) throws HibernateException, SQLException {
77 statement.setNull(index);
79 Integer pounds = value.pounds
80 statement.setInt(index, pounds);
84 public Object deepCopy(Object value) throws HibernateException {
88 public boolean isMutable() {
92 public Serializable disassemble(Object value) throws HibernateException {
93 return (Serializable) value;
96 public Object assemble(Serializable state, Object owner) throws HibernateException {
100 public Object replace(Object original, Object target, Object owner) throws HibernateException {
107 Weight(Integer pounds)
115 class UserTypeMappingTestsPerson {
121 static constraints = {
123 weight(nullable: true)
128 weight( type:WeightUserType)
138 void testCustomUserType() {
139 def personClass
= ga
.getDomainClass("UserTypeMappingTestsPerson").clazz
140 def weightClass
= ga
.classLoader
.loadClass("Weight")
142 def person
= personClass
.newInstance(name
:"Fred", weight
:weightClass
.newInstance(200))
144 person
.save(flush
:true)
147 person
= personClass
.get(1)
151 assertEquals
200, person
.weight
.pounds
154 void testUserTypeMapping() {
156 def clz
= ga
.getDomainClass("UserTypeMappingTest").clazz
159 assert clz
.newInstance(active
:true).save(flush
:true)
161 DataSource ds
= (DataSource
)applicationContext
.getBean('dataSource')
165 con
= ds
.getConnection()
166 def statement
= con
.prepareStatement("select * from type_test")
167 def result
= statement
.executeQuery()
169 def value
= result
.getString('active')
171 assertEquals
"Y", value