PostgreSQL UUID supportato da Hibernate?
-
12-10-2019 - |
Domanda
non riesco a lavorare con Hibernate java.util.UUID per PostgreSQL.
Questa è la mappatura utilizzando javax.persistence * annotazioni:.
private UUID itemUuid;
@Column(name="item_uuid",columnDefinition="uuid NOT NULL")
public UUID getItemUuid() {
return itemUuid;
}
public void setItemUuid(UUID itemUuid) {
this.itemUuid = itemUuid;
}
Quando persistere un oggetto transiente ottengo uno SQLGrammarException:
column "item_uuid" is of type uuid but expression is of type bytea at character 149
versione di PostgreSQL è 8.4.4
Driver JDBC - 8.4.4-702 (provato anche 9.0 - stessa cosa)
versione Hibernate è 3.6, principali proprietà di configurazione:
<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>
Soluzione
Questo può essere risolto aggiungendo la seguente annotazione all'UUID:
import org.hibernate.annotations.Type;
...
@Type(type="pg-uuid")
private java.util.UUID itemUuid;
Per quanto riguarda il motivo per cui Hibernate non si limita a rendere questa impostazione predefinita, non ho potuto voi ...
raccontareUPDATE: Ci sembrano essere ancora problemi con il metodo createNativeQuery a oggetti aperti che hanno campi UUID. Fortunatamente, il metodo createQuery finora ha funzionato bene per me.
Altri suggerimenti
Si tenta di persistere oggetto di tipo UUID, che non è annotato hibernate-entità. Così l'ibernazione vuole serializzare ad array di byte (tipo blob). Questo è il motivo per cui si ottiene questo messaggio 'espressione di tipo bytea'.
È possibile memorizzare UUID come macchie nel database (non raffinato), o fornire il vostro serializzatore personalizzato (molto lavoro) o convertire manualmente quell'oggetto. classe UUID ha metodi fromstring e toString, quindi vorrei conservarlo come stringa.
Come altri hanno detto, la soluzione a questo problema è quello di aggiungere un'annotazione @Type(type = "pg-uuid")
. Tuttavia, questo tipo non è compatibile con i tipi UUID di altri fornitori, per cui questa legami vostre classi Hibernate per Postgres. Per ovviare a questo, è possibile inserire questa annotazione in fase di esecuzione. Il sotto lavori per Hibernate 4.3.7.
In primo luogo, è necessario inserire un provider di metadati personalizzati per inserire le annotazioni. Fare questo come il primo passo dopo la creazione di un'istanza della classe 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()));
}
Questo fornitore di metadati personalizzati ritrova campi e metodi di tipo UUID
. Se ne trova uno, si inserisce un'istanza dell'annotazione org.hibernate.annotations.Type
affermando che il tipo dovrebbe essere "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;
}
}
}
Soluzione per qualcuno che non utilizzano JPA.
Prima:
<property name="testId" >
<column name="test_id" sql-type="uuid" not-null="true"/>
</property>
Dopo:
<property name="testId" column="test_id" type="org.hibernate.type.PostgresUUIDType">
</property>