views:

56

answers:

1

I am trying to use UUID in Hibernate.

Have the following Entity base-class description (with @MappedSuperclass annotation):

@Id @Column(name="id") private UUID id;

public UUID getId() { return id; }

For test, I am trying to read all entities of my class from database (database exists, records exist). My database is PostgreSQL 8.4 with UUID support and primary key is of UUID type.

Running my test I get the following in log:

[junit] 14:21:34,839  INFO LongType:203 - could not read column value from result set: id0_0_; Bad value for type long : d46668b8-e494-42ba-803f-c43524ac3f31

...

[junit] org.postgresql.util.PSQLException: Bad value for type long : d46668b8-e494-42ba-803f-c43524ac3f31
[junit]     at org.postgresql.jdbc2.AbstractJdbc2ResultSet.toLong(AbstractJdbc2ResultSet.java:2796)
[junit]     at org.postgresql.jdbc2.AbstractJdbc2ResultSet.getLong(AbstractJdbc2ResultSet.java:2019)
[junit]     at org.postgresql.jdbc2.AbstractJdbc2ResultSet.getLong(AbstractJdbc2ResultSet.java:2431)
[junit]     at org.apache.commons.dbcp.DelegatingResultSet.getLong(DelegatingResultSet.java:240)
[junit]     at org.hibernate.type.LongType.get(LongType.java:51)
[junit]     at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:184)
[junit]     at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:173)
[junit]     at org.hibernate.loader.Loader.getKeyFromResultSet(Loader.java:1121)

Looks like Hibernate doesn't really use UUID type it may parse from my entity annotated description. The same situation with Spring instead of UUID.

How else I can tell Hibernate I would like to user either UUID or String instead of Long for primary key?

PS: Hibernate I use 3.3.2.GA. I don't use EntityManager. I describe mapping with annotations and configure Hibernate with Spring.

A: 

I would typify the key as String:

private UUID id;

@Id
@Column(name="id")
public String getId()
{
    return id.toString();
}

public void setId(String value)
{
    id = UUID.fromString(value);
}

public UUID idAsUUID()
{
    return id;
}
splash
I wrote I did this, looks like the problem is not in mapping (UUID or String) but in conversion from PostgreSQL UUID type to Hibernate UUID or String type.
Take my comment back - I had problems with buildsystem, so hibernate was really thinking @Id was Long. I tried String, and really rebuild the whole system and it works. For working with real UUID I found http://opensource.atlassian.com/projects/hibernate/browse/HHH-3579 - there is no support yet (can be done manually) but will be soon.
BASOR ... it should give an extra badge for an accepted answer with negative voting. ;-)
splash
Cannot change this - StackOverflow has locked voting "until answer is changed".