Unable to store UUIDs in H2 2.0.202 with Hibernate
Asked Answered
B

2

9

We have been using H2 for our integration tests for quite some time. Now that H2 2.0.202 is out, we are trying to upgrade our codebase to it. We are unable to persist entities, that use java.util.UUID as a type. Consider the following example

public class MyEntity {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private UUID id;
}

If we try to save it in an H2 database using Hibernate, this fails with a JdbcSQLDataException with the message Value too long for column. The test is as simple as

@DataJpaTest
class H2Test {

  @Autowired MyRepository myRepository;

  @Test
  void testSave() {
    myRepository.save(new MyEntity());
    Assertions.assertThat(myRepository.findAll()).hasSize(1);
  }
}

You can find the full stack trace on PasteBin.

We are using the org.hibernate.spatial.dialect.h2geodb.GeoDBDialect, and this seems to be one of the causes of this problem. If we remove it, the simple test case above works fine, unfortunately we are using spatial data, so we need this dialect. I wonder if this is simply a missing compatibility between H2 2.0.202 and Hibernate? Or is there something we could do in our configuration? I could not find an issue that matches this problem in the hibernate jira, and somehow I cannot create one either.

Brocky answered 1/12, 2021 at 14:12 Comment(0)
C
25

I'm pretty sure that cause is a clash between the UUID and the Geometry types in Hibernate / Hibernate Spatial.See e.g. this issue: https://hibernate.atlassian.net/browse/HHH-11490

This problem should be resolved in versions 5.4.31 and later.

It can also be solved by annotating the id member variable with an explicit @Column(columnDefinition = "uuid") annotation.

Contactor answered 2/12, 2021 at 20:7 Comment(2)
Oh wow, that is an old issue. I did search for Hibernate issues, but discarded everything that was older than a few months... Thank you for digging this up, I will check if this is actually the case on Monday when I am back at work.Brocky
Setting @Column(columnDefinition = "uuid") actually resolved an issue I was having with the embedded H2 Spring Boot Test DB not returning any Results when querying by uuid. Thank You.Burin
H
5

I solved this with

  @Id
  @GeneratedValue(generator = "UUID")
  @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
  @Column(name = "id", updatable = false, nullable = false)
  @Type(type = "org.hibernate.type.UUIDCharType") // <-------------------------- THIS LINE
  private UUID id;
Humanoid answered 6/6, 2022 at 21:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.