【问题标题】:FindByUUID() using Spring Data's JPA RepositoryFindByUUID() 使用 Spring Data 的 JPA 存储库
【发布时间】:2013-08-23 09:29:53
【问题描述】:

由于某种原因,我无法为此找到合适的答案。我有以下简单实体:

@Entity
@Table(name = "simple_entity")
@Access(AccessType.FIELD)
public class SimpleEntity {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  protected Long id;

  @Column(unique = true, updatable = false)
  protected UUID uuid;

  @PrePersist
  protected void onCreateAbstractBaseEntity() {
      this.uuid = UUID.randomUUID();
  }

  public Long getId() {
      return this.id;
  }

  public UUID getUuid() {
      return this.uuid;
  }
}

带有 Hibernate 的 Spring Data JPA 可以在我的 MySQL 数据库中正确创建所有内容。但是,当我尝试使用我的 JPARepository 实现来使用它的 uuid 搜索一个项目时,它永远不会找到任何东西,即使它在数据库上执行 find 查询(我可以在我的调试器中看到)。这是我的 JPARepository 实现:

public interface SimpleEntityRepository extends JpaRepository<SimpleEntity, Long> {
      SimpleEntity findOneByUuid(UUID uuid);
}

这里是调用这个方法的控制器。

@Controller
@RequestMapping("/simple_entity")
public class SimpleEntityController {

@Autowired
private SimpleEntityRepository repository;

@RequestMapping(method = RequestMethod.GET, value = "/{simpleEntityId}", produces =        MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<FileDatastore> getSimpleEntity(@PathVariable UUID simpleEntityId)     {
    SimpleEntity record = this.repository.findOneByUuid(simpleEntityId);
    HttpHeaders headers = new HttpHeaders();

    HttpStatus status = (record != null) ? HttpStatus.OK : HttpStatus.NOT_FOUND;

    return new ResponseEntity<>(record, headers, status);
}

我错过了什么吗?

感谢您的帮助!

【问题讨论】:

  • 向我们展示您调用该方法的实现和相关代码。

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


【解决方案1】:

尝试使用 @org.hibernate.annotations.Type(type="org.hibernate.type.UUIDCharType") 注释您的 UUID 属性

@org.hibernate.annotations.Type(type="org.hibernate.type.UUIDBinaryType")

由于 MSB/LSB 与 UUID 以二进制格式交换,我在使用 UUID 查询数据库时遇到了类似的问题;我们解决了将数据视为字符串的问题,并在转换前进行必要的转换。

【讨论】:

  • 你的意思是注释字段:受保护的UUID uuid;用那个?
【解决方案2】:

将二进制列更改为字符串。默认为二进制,您必须添加此附加注释

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

例如。

@Id
@GeneratedValue
@Type(type="org.hibernate.type.UUIDCharType")
public UUID id;

【讨论】:

    【解决方案3】:

    遇到了同样的问题,特别是它在 H2 中有效,但在 MySQL 中无效。

    此外,由于 Hibernate(在 JPA 下)正在查询该记录是否存在但它没有找到它,所以我在尝试更新记录时遇到了 PRIMARY 键约束失败。

    使用 @Column(length=16) 也可以巧妙地解决这个问题,假设 MySQL 使用的是 BINARY 列...否则匹配将失败,因为该列在 DB 中有额外的数据(我认为它默认为 BINARY[ 32])。

    【讨论】:

      【解决方案4】:

      我最近解决了同样的问题,如果有人在这里偶然发现,我的解决方案是用

      注释列
      @Column(name = "id", columnDefinition = "BINARY(16)")
      private UUID id;
      

      这为我解决了问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-06
        • 2018-06-15
        • 2015-07-13
        • 2016-12-26
        • 1970-01-01
        • 2018-10-06
        相关资源
        最近更新 更多