Hibernate支持Postgresql UUID?

时间:2010-12-21 00:17:16

标签: java hibernate postgresql orm hibernate-mapping

我不能让Hibernate使用PostgreSQL的java.util.UUID。

这是使用javax.persistence的映射。* annotations:

private UUID itemUuid;

@Column(name="item_uuid",columnDefinition="uuid NOT NULL")
public UUID getItemUuid() {
    return itemUuid;
}

public void setItemUuid(UUID itemUuid) {
    this.itemUuid = itemUuid;
}

当持久化对象时,我得到一个SQLGrammarException:

column "item_uuid" is of type uuid but expression is of type bytea at character 149

PostgreSQL版本是8.4.4
JDBC驱动程序 - 8.4.4-702(也试过9.0 - 同样的事)
Hibernate版本是3.6,主要配置属性:

<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://192.168.1.1/db_test</property>

5 个答案:

答案 0 :(得分:32)

这可以通过在UUID中添加以下注释来解决:

import org.hibernate.annotations.Type;
...
@Type(type="pg-uuid")
private java.util.UUID itemUuid;

至于为什么Hibernate不会将其设为默认设置,我无法告诉你......

更新: 使用createNativeQuery方法打开具有UUID字段的对象似乎仍存在问题。幸运的是,到目前为止,createQuery方法对我来说很好。

答案 1 :(得分:5)

您尝试持久化UUID类型的对象,该对象不是带有hibernate注释的实体。所以hibernate想要将它序列化为字节数组(blob类型)。这就是为什么你得到这个消息'类型为bytea'的表达式。

您可以将UUID作为blob存储在数据库中(不是优雅的),或者提供自定义序列化程序(很多工作)或手动转换该对象。 UUID类有fromString和toString方法,所以我将它存储为String。

答案 2 :(得分:2)

正如其他人提到的,此问题的解决方案是添加@Type(type = "pg-uuid")注释。但是,此类型与其他供应商的UUID类型不兼容,因此这将您的Hibernate类与Postgres联系起来。要解决此问题,可以在运行时插入此批注。以下适用于Hibernate 4.3.7。

首先,您需要插入自定义元数据提供程序以插入注释。在创建Configuration类的实例后,这是第一步:

// Perform some test to verify that the current database is Postgres.
if (connectionString.startsWith("jdbc:postgresql:")) {
    // Replace the metadata provider with our custom metadata provider.
    MetadataProviderInjector reflectionManager = MetadataProviderInjector)cfg.getReflectionManager();
    reflectionManager.setMetadataProvider(new UUIDTypeInsertingMetadataProvider(reflectionManager.getMetadataProvider()));
}

此自定义元数据提供程序查找UUID类型的字段和方法。如果找到一个,则会插入org.hibernate.annotations.Type注释的实例,声明该类型应为"pg-uuid"

package nl.gmt.data;

import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.common.reflection.AnnotationReader;
import org.hibernate.annotations.common.reflection.MetadataProvider;

import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

class UUIDTypeInsertingMetadataProvider implements MetadataProvider {
    private final Map<AnnotatedElement, AnnotationReader> cache = new HashMap<>();
    private final MetadataProvider delegate;

    public UUIDTypeInsertingMetadataProvider(MetadataProvider delegate) {
        this.delegate = delegate;
    }

    @Override
    public Map<Object, Object> getDefaults() {
        return delegate.getDefaults();
    }

    @Override
    public AnnotationReader getAnnotationReader(AnnotatedElement annotatedElement) {
        // This method is called a lot of times on the same element, so annotation
        // readers are cached. We only cache our readers because the provider
        // we delegate to also caches them.

        AnnotationReader reader = cache.get(annotatedElement);
        if (reader != null) {
            return reader;
        }

        reader = delegate.getAnnotationReader(annotatedElement);

        // If this element is a method that returns a UUID, or a field of type UUID,
        // wrap the returned reader in a new reader that inserts the "pg-uuid" Type
        // annotation.

        boolean isUuid = false;
        if (annotatedElement instanceof Method) {
            isUuid = ((Method)annotatedElement).getReturnType() == UUID.class;
        } else if (annotatedElement instanceof Field) {
            isUuid = ((Field)annotatedElement).getType() == UUID.class;
        }

        if (isUuid) {
            reader = new UUIDTypeInserter(reader);
            cache.put(annotatedElement, reader);
        }

        return reader;
    }

    private static class UUIDTypeInserter implements AnnotationReader {
        private static final Type INSTANCE = new Type() {
            @Override
            public Class<? extends Annotation> annotationType() {
                return Type.class;
            }

            @Override
            public String type() {
                return "pg-uuid";
            }

            @Override
            public Parameter[] parameters() {
                return new Parameter[0];
            }
        };

        private final AnnotationReader delegate;

        public UUIDTypeInserter(AnnotationReader delegate) {
            this.delegate = delegate;
        }

        @Override
        @SuppressWarnings("unchecked")
        public <T extends Annotation> T getAnnotation(Class<T> annotationType) {
            if (annotationType == Type.class) {
                return (T)INSTANCE;
            }

            return delegate.getAnnotation(annotationType);
        }

        @Override
        public <T extends Annotation> boolean isAnnotationPresent(Class<T> annotationType) {
            return annotationType == Type.class || delegate.isAnnotationPresent(annotationType);
        }

        @Override
        public Annotation[] getAnnotations() {
            Annotation[] annotations = delegate.getAnnotations();
            Annotation[] result = Arrays.copyOf(annotations, annotations.length + 1);
            result[result.length - 1] = INSTANCE;
            return result;
        }
    }
}

答案 3 :(得分:1)

现在,您还可以使用java.util.UUID提供的UUID类,该类由Hibernate映射到Postgres的uuid数据类型,而在从数据库进行读/写操作时无需进行任何转换。

  @Id
  @GeneratedValue
  private UUID id;

默认情况下,生成的值是auto,这使您的JVM可以定义UUID。这也允许休眠使用批处理插入优化。

您可以配置数据库以设置UUID值。更多信息,请点击此处https://vladmihalcea.com/uuid-identifier-jpa-hibernate/

答案 4 :(得分:0)

不使用JPA的人的解决方案。

在:

<property name="testId" >
        <column name="test_id"  sql-type="uuid"  not-null="true"/>
</property>

后:

<property name="testId" column="test_id" type="org.hibernate.type.PostgresUUIDType">
</property>