【问题标题】:Spring boot JPA findByUuidSpring Boot JPA findByUuid
【发布时间】:2019-02-28 22:19:50
【问题描述】:

我想在数据库中查询不是主键的给定 UUID。我无法使其工作:

这是我的 Node 类。我的 PK 是一个长的自动增量,我有一个名为 uuid 的字段,用于存储在数据库中保存新节点时生成的 UUID 键。

更新:即使我通过 id 获得一个节点,然后我使用它的节点 uuid 调用 findByUuid 函数,我得到一个空值

    Node n = nodeService.getNodeByNodeId(1L);
    return nodeService.getNodeByNodeUuid(n.getApiKey());

节点

@Entity
@Table(name="node")
public class Node {

@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.AUTO, generator = "node_seq")
@SequenceGenerator(name = "node_seq", sequenceName = "node_seq", allocationSize = 1)
private Long id;

@Column(name = "uuid", updatable = false, nullable = false, unique=true)
private UUID uuid;


public UUID getUuid() {
    return uuid;
}

public void setUuid(UUID uuid) {
    this.uuid = uuid;
}

@Column(name = "NAME", length = 50, unique = true)
@NotNull    
private String name;

@OneToMany(mappedBy="node", cascade=CascadeType.ALL)
private List<User> users;

public List<User> getUsers() {
    return users;
}

public void setUsers(List<User> users) {
    this.users = users;
}
public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}

控制器

    @PreAuthorize("hasRole('MANAGER')")
    @RequestMapping(value="/node/{nodeUuidString}", method = RequestMethod.GET)
    public Node getNodeByUuid(@PathVariable UUID nodeUuidString) {
       return nodeService.getNodeByNodeUuid(nodeUuidString);
}

我还将 nodeUuidString 作为字符串,然后转换为 UUID:

UUID nodeUuid = UUID.fromString(nodeUuidString);

但是没有用。

服务

    public Node getNodeByNodeUuid(UUID nodeUuid) {
       return nodeRepository.findOneByUuid(nodeUuid);
}

存储库

@Repository
public interface NodeRepository extends CrudRepository<Node, Long> {

Node findOneByUuid(UUID nodeUuid);

}

【问题讨论】:

  • 显示节点类。而且当你说它不起作用时,你会发生什么异常?
  • 我认为你不需要 findOneByUuid 尝试将其更改为 findByUuid
  • 我与findByUuidfindOneByUuid 的结果相同
  • 不工作是什么意思?你有什么异常吗??
  • 不,我只是得到一个空值。

标签: spring spring-data-jpa uuid


【解决方案1】:

Spring 将数据库中的字段创建为二进制 (255)

正确的是二进制(16)

因此,为了使查询正常工作,我必须在实体定义上使用此注释:

@Column(name = "apiKey", updatable = false, nullable = false, unique=true, columnDefinition = "BINARY(16)")

【讨论】:

    【解决方案2】:

    其背后的原因是默认情况下休眠将UUID 转换为BINARY(255) 255 作为默认长度值。 UUID 的大小实际上是BINARY(16)。因此在比较时会导致不匹配。

    解决方案是使用如下指定列的长度

    @Column(length=16)
    UUID uuid;
    

    注意:如果你使用的不是spring生成的sql数据库,则需要修改id列

    alter table table_name modify column uuid binary(16);
    

    【讨论】:

      【解决方案3】:

      如果没有任何效果,只需编写您自己的查询:

      @Query("SELECT n FROM Node n WHERE n.uuid= ?1")
      Node findOneByUuid(UUID nodeUuid);
      

      【讨论】:

      • 感谢您的回答,但它仍然给我 null。
      猜你喜欢
      • 2013-08-23
      • 2017-09-17
      • 2018-07-10
      • 2021-04-02
      • 2017-07-04
      • 2020-09-12
      • 1970-01-01
      • 2017-05-09
      • 2021-01-18
      相关资源
      最近更新 更多