gpt4 book ai didi

java - Spring JpaRepository getOne() 用于 PK 为字符串的表

转载 作者:行者123 更新时间:2023-12-02 09:57:25 25 4
gpt4 key购买 nike

我正在将 Spring Boot 与 JpaRepository 结合使用。我有一个用字符串 PK 定义的表。

CREATE TABLE mytable (
uuid uuid DEFAULT gen_random_uuid() PRIMARY KEY,
url text NOT NULL,
status status DEFAULT 'pending' NOT NULL,
created_at timestamp with time zone DEFAULT now() NOT NULL
);

问题

在 JpaRepository 中,如何执行与 getOne(uuid) 等效的操作? (getOne(uuid) 接收一个参数类型 Long),即如何检索 String 类型的 uuid 的一行?

代码

@Entity
@Table(name = "mytable")
public class MyTableEntity {

public enum Status {
pending,
complete,
processing,
failed
}

@Id
@Column(name = "uuid")
//@GeneratedValue(strategy = GenerationType.AUTO)
private String uuid;

@Column(name = "url", nullable = false)
private String url;

@Enumerated(EnumType.STRING)
@Column(columnDefinition = "photo_status", nullable = false)
//@Type( type = "pgsql_enum" )
private Status status;

@Column(name = "created_at", nullable = false)
private LocalDateTime created_at;

存储库

public interface MyRepository extends JpaRepository<MyTableEntity, Long> {
}

最佳答案

因此,如果您的实体有 String 键,您可以使用 Repository 的此类声明:

@Repository
public interface MyRepository extends JpaRepository<MyTableEntity, String> {
}

现在,如果您想通过 id 获取实体,其类型为 String,您可以使用例如:

private void someMethod() {
UUID uuid = UUID.randomUUID();
MyTableEntity myEntity = myRepository.getOne(uuid.toString());
}

如果您查看JpaRepository定义,它期望第一个类型是您的实体类,第二个是该实体的键的类型:

public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T>

关于java - Spring JpaRepository getOne() 用于 PK 为字符串的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55890119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com