2017-07-17 51 views
1

我正在开发Spring REST服务(使用Spring Data JPA),而我的实体包含java.util.UUID类型的属性。我正在使用MySQL作为导致问题的数据库。目前为止一切正常,除了存储库方法,其中UUID是查询的一部分,例如:entityRepository.findByUuid(UUID uuid);使用Hibernate时,findByUuid()在MySQL-DB中不起作用

默认情况下,数据存储在二进制(255)列中。从存储库获取UUID工作正常,唯一的问题是在查询中使用UUID,例如在findByUuid()中。它总是告诉我它无法在数据库中找到特定的UUID。 MariaDB出现同样的问题。

我的服务适用于H2-数据库。任何想法为什么MySQL(和MariaDB)有这个问题?

DB-配置:

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的实体来说

@Entity 
public class Thema { 
    // without any annotations, works fine with H2 Database 
    private UUID uuid; 
... 
+0

你需要看的日志文件,并调查其使用JPA在SQL查询的问题,把@Convert每个UUID场,注册一个全局属性转换器。尝试直接在DB-client中运行提取的查询。 –

+0

你有没有提到这[后](https://stackoverflow.com/questions/18350154/findbyuuid-using-spring-datas-jpa-repository)。可能会有所帮助。 –

回答

0

我发现要做的仅仅是转换UUID为一个字符串插入到数据库最简单的事情。毫无疑问,在数据库中占用更多的空间,但我无法找到其他任何可行的方法。

为了避免由@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); 
    } 
} 
相关问题