5

I'm developing a Spring REST Service (with Spring Data JPA) and my entity's contains properties of type java.util.UUID. I'm using MySQL as a database which causes problems. Everything works fine so far except repository-methods where a UUID is part of a query, e.g.: entityRepository.findByUuid(UUID uuid);

The data is stored in a binary(255)-column by default. Get the UUID from the repository works fine, the only problem is to use a UUID in queries, like in findByUuid(). It always tells me that it can't find a specific UUID in the database. The same problem happens with MariaDB.

My service works properly with H2-Database. Any idea why MySQL (and MariaDB) has this problem?

DB-Config:

spring.datasource.url=jdbc:mysql://localhost/abc123
spring.datasource.username=alfkmakfaf
spring.datasource.password=aafkmafmlaf
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database=mysql
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

UUID in Entitys

@Entity
public class Thema {
    // without any annotations, works fine with H2 Database
    private UUID uuid;
...
Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
phip1611
  • 5,460
  • 4
  • 30
  • 57
  • You need to watch the log file and investigate the problem in SQL query which is used by JPA. Try to run extracted query directly in DB-client. – J-Alex Jul 17 '17 at 22:06
  • have you referred this [post](https://stackoverflow.com/questions/18350154/findbyuuid-using-spring-datas-jpa-repository).may be it will be helpful. – Rajith Pemabandu Jul 18 '17 at 00:37

2 Answers2

1

I have this problem with binary UUID (default column is binary type) if I add this addnotation in model (change binary to String column) begin working

@Type(type="org.hibernate.type.UUIDCharType")
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
0

I've found the easiest thing to do is just convert UUID into a string to insert into db. No doubt takes up more space in db but I cant find anything else that works.

To avoid having to put @Convert on every UUID field, register a global attribute converter by @Converter(autoApply = true)

@Converter(autoApply = true)
public class UUIDConverter implements AttributeConverter<UUID, String> {

    @Override
    public String convertToDatabaseColumn(UUID uuid) {
        return uuid.toString();
    }

    @Override
    public UUID convertToEntityAttribute(String s) {
        return UUID.fromString(s);
    }
} 
reversebind
  • 1,216
  • 1
  • 14
  • 18