adamB
adamB

Reputation: 53

How do you write a query in JPA repository in Spring Boot?

I'm trying to pull a single string from my sql table using a query in my JPA repository. I have a repository, service, and controller class. My repository query looks like

@Query(value = "SELECT title FROM table_name WHERE subject = term;", nativeQuery = true)
String getTitleBySubject(String term);

My service method looks like this

public String getTitleBySubject(String term) {
    String title = (String) repo.getTitleBySubject(term);
    return title;
}

My controller call is

service.getTitleBySubject("subject");

Why does this return null? This is printed to the console

enter image description here

Upvotes: 5

Views: 2432

Answers (1)

Vy Do
Vy Do

Reputation: 52516

Change

@Query(value = "SELECT title FROM table_name WHERE subject = term;", nativeQuery = true)
String getTitleBySubject(String term);

to

@Query(value = "SELECT title FROM table_name WHERE subject = ?1", nativeQuery = true)
String getTitleBySubject(String term);

Reference document: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.at-query

Upvotes: 2

Related Questions