我正在使用带有JpaRepository的Spring Boot。我有一个用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定义,则它期望第一个类型是您的Entity类,第二个是该实体的键的类型:

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

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

10-12 03:05