简体   繁体   中英

How to reference entity in Query in CrudRepository in Spring Data JDBC?

I want to fetch Entity from Database with Spring Data CrudRepository with a findWithTitle() method like this:

interface TasksCrudRepository extends CrudRepository<Task, Long> {

    @Query(value = "SELECT t FROM Task t WHERE t.title IS NOT NULL")
    List<Task> findWithTitle();
}

But I get

org.h2.jdbc.JdbcSQLSyntaxErrorException: Column "T" not found; SQL statement:
SELECT t FROM Task t [42122-199]

I can't find the cause why is that happening. From what I know this syntax should be working as expected.

This is how Task entity looks like:

@Data
@Table("task")
@AllArgsConstructor
public class Task {
    @Id
    private Long id;
    private String title;
    private String description;
    private Set<Attachment> attachments;
    private Set<TagRef> tagRefs;
    @CreatedDate
    private LocalDateTime createdAt;
    @LastModifiedDate
    private LocalDateTime updatedAt;
}

And here's the schema for it:

CREATE TABLE task
(
    id          IDENTITY,
    title       VARCHAR(100),
    description VARCHAR(1024),
    created_at  TIMESTAMP,
    updated_at  TIMESTAMP,
);

Instead of Custom query use predefined Spring JPA method.
Please try the below approach.

interface TasksCrudRepository extends CrudRepository<Task, Long> {


    List<Task> findByTitleNotNull();
}

Modifications done:

  • Removed Query annoytation
  • Renamed the method to match JPA standard predefined service

The solution is to use asterisk as @deHaar mentioned:

@Query("SELECT * FROM Task t ...")
List<Task> findTasks();
}

What is more if you want to perform JOIN query it is also possible to run with asterisk as well:

@Query("SELECT * FROM Task t JOIN Attachment a ON t.id = a.task")
List<Task> findWithAttachments();

May be this will help you, COLUMN_NOT_FOUND_1 = 42122 The error with code 42122 is thrown when referencing an non-existing column. Example: CREATE TABLE TEST(ID INT); SELECT NAME FROM TEST;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM