Hi,
unfortunately, I have not found any solution to use PostgreSQL with it's native type uuid (which should be mapped to java.util.UUID). That is why I am going to describe my solution (could probably be mapped to EclipseLink,too). Hopefully, this will help somebody.
UserType:
Dialect:Code:public class UuidUserType implements UserType { @SuppressWarnings( "unchecked" ) public Class returnedClass() { return UUID.class; } public int[] sqlTypes() { return new int[] { Types.OTHER }; } public boolean equals( Object x, Object y ) throws HibernateException { return (x == y) || (x != null && y != null && (x.equals(y))); } public Object nullSafeGet( ResultSet rs, String[] names, Object owner ) throws HibernateException, SQLException { return rs.getObject(names[0]); } public void nullSafeSet( PreparedStatement st, Object value, int index ) throws HibernateException, SQLException { if ( value == null ) { st.setNull( index, Types.OTHER ); return; } else { st.setObject(index, value); } } public Object assemble( Serializable cached, Object owner ) throws HibernateException { return deepCopy(cached); } public Serializable disassemble( Object value ) throws HibernateException { return (UUID) deepCopy(value); } // UUID is immutable, so we do not copy it actually public Object deepCopy( Object value ) throws HibernateException { return (UUID) value; } public int hashCode( Object x ) throws HibernateException { return x.hashCode(); } public boolean isMutable() { return false; } public Object replace( Object original, Object target, Object owner ) throws HibernateException { return original; } }
ExampleEntity:Code:public class PostgreSQLDialectUuid extends PostgreSQLDialect { public PostgreSQLDialectUuid() { super(); registerColumnType(Types.OTHER, "uuid"); } }
When using Spring, your configuration could look like:Code:@Entity @TypeDef( name="UUIDUserType", typeClass = UuidUserType.class) @NamedQueries({ @NamedQuery(name="deleteUuidEntities", query="delete from UuidEntity u"), @NamedQuery(name="selectUuidEntities", query="select u from UuidEntity u") }) public class UuidEntity { @Id @Type(type="UUIDUserType") private UUID id = UUID.randomUUID(); public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } }
Sources (including testcases) are attachedCode:<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" p:dataSource-ref="dataSource" p:persistenceUnitName="test"> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="showSql" value="true" /> <property name="databasePlatform" value="PostgreSQLDialectUuid" /> </bean> </property> </bean>
Kind regards
Matthias


Reply With Quote
