Jpa findAllBy* 使用 Long id 而不是实体

Jpa findAllBy* using Long id instead of an entity

我只是不想做:

myEntity = findById(Long id)
findAllByEntityAnd*(MyEntity myEntity, *)

相反,我想做:

findAllByEntityAnd*(Long entityId, *)

我是否错过了实现我想要的东西,或者我无法直接实现它?

感谢帮助~

当我尝试时,Spring提示我:

java.lang.IllegalArgumentException: Could not create query metamodel for method public abstract java.util.List com.worksap.morphling.raptor.dump.thread.dao.ThreadDoRepository.findAllByDumpDoAndLocksWaitingContains(java.lang.Long,java.lang.String)!

这是我的table供您参考:

@Data
@Builder
@Entity
@Table(name = "thread_info")
@AllArgsConstructor
@NoArgsConstructor
public class ThreadDo implements Serializable {
    private static final long serialVersionUID = -1L;
    String name;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @ManyToOne
    @JoinColumn(name = "thread_dump_id")
    @JsonIgnore
    private ThreadDumpDo dumpDo;

    ...
}

@Data
@Builder
@Entity
@Table(name = "thread_dump")
@AllArgsConstructor
@NoArgsConstructor
public class ThreadDumpDo implements Serializable {
    private static final long serialVersionUID = -1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToMany(
            mappedBy = "dumpDo",
            cascade = CascadeType.ALL,
            orphanRemoval = true
    )
    private List<ThreadDo> threadDoList;
}

然后我有一个 ThreadDoRepository 并想像这样直接定位 threadDos:

List<ThreadDo> findAllByDumpDoAndLocksWaitingContains(Long dumpId, String lockWaiting);

我可以通过 @Query 实现它,如下所示,但我真的认为它很丑陋,因为它很容易解释(我认为)。

@Query(value = "select * from thread_info t where t.thread_dump_id = ?1 and t.locks_waiting like ?2",
            nativeQuery = true)
List<ThreadDo> findAllByDumpDoAndLocksWaitingContains(Long dumpId, String lockWaiting);

试试这个

List<ThreadDo> findAllByDumpDo_IdAndLocksWaitingContains(Long dumpId, String lockWaiting);