【问题标题】:findByUuid() doesn't work in MySQL-DB when using Hibernate使用 Hibernate 时 findByUuid() 在 MySQL-DB 中不起作用
【发布时间】:2017-12-22 14:05:21
【问题描述】:

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

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

我的服务与 H2-Database 一起正常工作。知道为什么 MySQL(和 MariaDB)会出现这个问题吗?

数据库配置:

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;
...

【问题讨论】:

  • 您需要查看日志文件并调查 JPA 使用的 SQL 查询中的问题。尝试直接在 DB-client 中运行提取的查询。
  • 你有没有提到这个post。可能会有帮助。

标签: java mysql spring hibernate spring-data-jpa


【解决方案1】:

如果我在模型中添加这个附加注释(将二进制更改为字符串列)开始工作,我会遇到二进制 UUID 的问题(默认列是二进制类型)

@Type(type="org.hibernate.type.UUIDCharType")

【讨论】:

    【解决方案2】:

    我发现最简单的方法就是将 UUID 转换为字符串以插入到 db 中。毫无疑问,在 db 中占用了更多空间,但我找不到其他任何可行的方法。

    为避免必须在每个 UUID 字段上放置 @Convert,请通过 @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);
        }
    } 
    

    【讨论】:

      猜你喜欢
      • 2011-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-29
      • 2021-05-31
      • 2014-07-14
      • 2021-05-22
      相关资源
      最近更新 更多