为UUID配置Grails / Hibernate / Postgres

时间:2011-12-09 23:09:14

标签: hibernate postgresql grails uuid

所以我正在尝试创建一个grails应用程序,该应用程序挂钩到主键列为UUID的现有数据库中:

      Column       |            Type             | Modifiers 
-------------------+-----------------------------+-----------
 uuid              | uuid                        | not null

但是,当我设置这样的数据源时:

class DataStore {
UUID     uuid
...
static mapping = {
...
     id generator: 'assigned', name: 'uuid', type: 'pg-uuid'
}

它坚持认为uuid列是varchar(255)。我不知道我要做些什么才能让它认识到uuid列是一个uuid列,并且我已经尝试将一个UserType类放在src / groovy /中,但是这并没有解决任何问题。

我也试图用inet列做同样的事情,但我在这里一步一步。

这里有什么帮助吗?我现在已经结束了。

编辑:我发现了这个grails using uuid as id and mapping to to binary column,但是当我尝试现在运行它时它只会抛出此错误:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Invocation of init method failed; nested exception is org.codehaus.groovy.grails.exceptions.GrailsDomainException: Error evaluating ORM mappings block for domain [cstools.domain.DataStore]:  No such property: UUIDUserType for class: org.codehaus.groovy.grails.orm.hibernate.cfg.HibernateMappingBuilder
... 23 more

UUIDUserType.groovy

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.UUID;
import org.hibernate.HibernateException;

public class UUIDUserType implements org.hibernate.usertype.UserType {

    private static final String CAST_EXCEPTION_TEXT = " cannot be cast to a java.util.UUID.";

    /*
     * (non-Javadoc)
     * 
     * @see org.hibernate.usertype.UserType#assemble(java.io.Serializable,
     *      java.lang.Object)
     */
    public Object assemble( Serializable cached, Object owner ) throws HibernateException {

        if ( !String.class.isAssignableFrom( cached.getClass() ) ) {
            return null;
        }

        return UUID.fromString( (String) cached );
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.hibernate.usertype.UserType#deepCopy(java.lang.Object)
     */
    public Object deepCopy( Object value ) throws HibernateException {

        if ( !UUID.class.isAssignableFrom( value.getClass() ) ) {
            throw new HibernateException( value.getClass().toString() + CAST_EXCEPTION_TEXT );
        }

        UUID other = (UUID) value;

        return UUID.fromString( other.toString() );
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.hibernate.usertype.UserType#disassemble(java.lang.Object)
     */
    public Serializable disassemble( Object value ) throws HibernateException {

        return value.toString();
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.hibernate.usertype.UserType#equals(java.lang.Object,
     *      java.lang.Object)
     */
    public boolean equals( Object x, Object y ) throws HibernateException {

        if ( !UUID.class.isAssignableFrom( x.getClass() ) ) {
            throw new HibernateException( x.getClass().toString() + CAST_EXCEPTION_TEXT );
        }
        else if ( !UUID.class.isAssignableFrom( y.getClass() ) ) {
            throw new HibernateException( y.getClass().toString() + CAST_EXCEPTION_TEXT );
        }

        UUID a = (UUID) x;
        UUID b = (UUID) y;

        return a.equals( b );
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.hibernate.usertype.UserType#hashCode(java.lang.Object)
     */
    public int hashCode( Object x ) throws HibernateException {
        if ( !UUID.class.isAssignableFrom( x.getClass() ) ) {
            throw new HibernateException( x.getClass().toString() + CAST_EXCEPTION_TEXT );
        }

        UUID a = (UUID) x;

        return a.hashCode();
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.hibernate.usertype.UserType#isMutable()
     */
    public boolean isMutable() {

        return false;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.hibernate.usertype.UserType#nullSafeGet(java.sql.ResultSet,
     *      java.lang.String[], java.lang.Object)
     */
    public Object nullSafeGet( ResultSet rs, String[] names, Object owner ) throws HibernateException, SQLException {

        String value = rs.getString( names[0] );
        if ( value == null ) {
            return null;
        }
        else {
            return UUID.fromString( value );
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.hibernate.usertype.UserType#nullSafeSet(java.sql.PreparedStatement,
     *      java.lang.Object, int)
     */
    public void nullSafeSet( PreparedStatement st, Object value, int index ) throws HibernateException, SQLException {

        if ( value == null ) {
            st.setNull( index, Types.VARCHAR );
            return;
        }

        if ( !UUID.class.isAssignableFrom( value.getClass() ) ) {
            throw new HibernateException( value.getClass().toString() + CAST_EXCEPTION_TEXT );
        }

        st.setString( index, value.toString() );
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.hibernate.usertype.UserType#replace(java.lang.Object,
     *      java.lang.Object, java.lang.Object)
     */
    public Object replace( Object original, Object target, Object owner ) throws HibernateException {

        if ( !UUID.class.isAssignableFrom( original.getClass() ) ) {
            throw new HibernateException( original.getClass().toString() + CAST_EXCEPTION_TEXT );
        }

        return UUID.fromString( original.toString() );
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.hibernate.usertype.UserType#returnedClass()
     */
    @SuppressWarnings( "unchecked" )
    public Class returnedClass() {

        return UUID.class;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.hibernate.usertype.UserType#sqlTypes()
     */
    public int[] sqlTypes() {

        return int[] { Types.CHAR };
    }
}

1 个答案:

答案 0 :(得分:5)

编辑:此解决方案需要PostgreSQL 8.4或更高版本,相应的JDBC驱动程序8.4-703或更高版本以及Hibernate 3.6(对于内置的 pg-uuid 类型,自定义UserType应该使用先前的Hibernate版本)

刚刚发现您不需要自定义UserTypejava.util.UUID映射到PostgreSQL uuid。从Hibernate 3.6开始,您可以使用内置类型pg-uuid,这是org.hibernate.type.PostgresUUIDType的快捷方式(请参阅Hibernate 3.6 docs about basic types)。这种内置类型应该完全按照自定义UserType执行。

但我认为你必须使用 uuid2 生成器而不是 uuid 生成器。请参阅Hibernate 3.6 docs about generators。 uuid生成器创建UUID的String表示,而uuid2生成器能够生成值java.util.UUIDjava.lang.String或长度为16的字节数组(byte [16])。不过,我不知道如何配置uuid2生成器。我不使用这个生成器,只是在我的Entity基类的构造函数中分配一个随机的UUID。

因此,我认为您必须将代码更改为以下内容:

class DataStore {
UUID     uuid
...
static mapping = {
...
  id generator: 'assigned', name: 'uuid2', type: 'pg-uuid'
}