Java Spring JpaRepository getOne()用于PK为字符串的表
我正在使用带有JPA存储的Spring Boot。我有一个定义了PK的表,PK是一个字符串Java Spring JpaRepository getOne()用于PK为字符串的表,java,sql,jpa,spring-data-jpa,Java,Sql,Jpa,Spring Data Jpa,我正在使用带有JPA存储的Spring Boot。我有一个定义了PK的表,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 N
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> {
}
公共接口MyRepository扩展了JpaRepository{
}
因此,如果您的实体具有字符串键,您可以使用存储库的此类声明
:
@Repository
public interface MyRepository extends JpaRepository<MyTableEntity, String> {
}
如果查看JpaRepository
定义,它期望第一种类型是您的实体类,第二种类型是此实体的键的类型:
public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T>
公共接口JpaRepository扩展了分页和排序存储库,QueryByExampleExecutor
向我们显示您的存储库定义。如果需要较长时间,则表示您选择了Long作为存储库ID的通用类型,尽管它是一个字符串。只需使用正确的泛型类型。可能您正在搜索findById方法。(可选findById(ID primaryKey):返回给定ID的实体。)请参阅:@JBNizet,感谢您的回复。我有点困惑,因为gen_random_uuid()生成一个随机字符串。所以我想我不能把类型改成Long。(我无法更改SQL脚本)。向我们显示存储库类的定义,因为您可能在JpaRepository
中为主键类型指定了Long
作为泛型类型参数。
public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T>