Search code examples
springpostgresqlspring-data-jpajpql

Jpa findAllBy* using Long id instead of an entity


I just do not want to do:

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

instead I want do:

findAllByEntityAnd*(Long entityId, *)

Is there something I missed to achieve what I wanted or I just cannot achieve it directly?

Thanks for the help ~

When I tried it, the Spring prompted me:

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)!

Here is my table for your reference:

@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;
}

And then I have a ThreadDoRepository and want to locate the threadDos directly like this:

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

I can achieve it via @Query as follows, but I really think it's pretty ugly since it's easy to interpret (I think).

@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);

Solution

  • Try this

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