12

I want to use PostgreSQL's native UUID type with a Java UUID. I am using Hibernate as my JPA provider and ORM. If I try to save it directly, it is just saved as a bytea in Postgres.

How can I do this?

mainstringargs
  • 12,514
  • 35
  • 105
  • 170

6 Answers6

13

Try use the latest development version of the JDBC driver (Currently 8.4dev-700), or wait for the next release version. (Edited to add: 8.4-701 has been released)

The release notes mention this change:

Map the database uuid type to java.util.UUID. This only works for relatively new server (8.3) and JDK (1.5) versions.

Stephen Denne
  • 35,133
  • 10
  • 44
  • 60
  • 2
    This seems to be failing presently with the driver version 9.2-1002 and hibernate-core 3.3.1.GZ. There is a outstanding unanswered question at https://community.jboss.org/thread/229747?_sscc=t. I also run into a problem with this using GORM. – Peter N. Steinmetz Apr 03 '14 at 22:19
5

Here's a repost of my answer on Postgresql UUID supported by Hibernate? ... I know this question is old, but if someone stumbles across it, this will help them out.

This can be solved by adding the following annotation to the UUID:

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

As to why Hibernate doesn't just make this the default setting, I couldn't tell you...

UPDATE: There still seem to be issues using the createNativeQuery method to open objects that have UUID fields. Fortunately, the createQuery method so far has worked fine for me.

Community
  • 1
  • 1
Robyn P
  • 624
  • 9
  • 8
1

Try this

@Column(name = "UUID", nullable=false, insertable = false, columnDefinition="uuid DEFAULT uuid_generate_v4()")
private String uuid;
Rajesh Guptan
  • 207
  • 2
  • 3
1

you could try with:

 @Column(name="foo", columnDefinition="uuid") 

where columnDefinition is a fragment of native SQL

dfa
  • 111,277
  • 30
  • 187
  • 226
0

In non-JPA usage I'd create a UserType to format the UUID as a string that PostgreSQL accepts, then just give the name of the UserType implementation as the column type.

araqnid
  • 117,888
  • 23
  • 152
  • 133
0

Perhaps you can get UUID type to be auto-converted to a String (uuid.toString() should give the canonical 36-char representation)? DBs usually convert things reliably between Strings and native types.

StaxMan
  • 108,392
  • 32
  • 202
  • 235