0

Can somebody help how to compose a HQL query with JPA @Query on the following line?

"get me all books which has this author and are published after year X"

Consider a simple entity without relationship - more concern on the JPA @Query and HQL combination:

@Entity public class Book{ @Id public int id; public String title, public String authorName; public String yearOfPublish; ..... 

}

5
  • Can you please show your entity model Commented Nov 10, 2021 at 14:11
  • Yet to create...You can Consider a simple one with date of year as String Commented Nov 12, 2021 at 5:38
  • Without the entity model I cannot tell you how the query should look like. Commented Nov 12, 2021 at 7:21
  • You are mentioning @Query. Do you use Spring DataJPA? Commented Nov 13, 2021 at 15:55
  • Yes. Im using Spring Data JPA Repository...Assume I defined a method: List<Book> getBooksByAuthorAnd GreaterThenYear(String authorName, String year ) Commented Nov 14, 2021 at 5:34

1 Answer 1

1

The query would be:

select b from Book b where b.authorName = :authorName and yearOfPublish > :year 

And as you are using Spring Data JPA you don't even need to write the Query! Simply write a method:

List<Book> findAllByAuthorNameAndYearOfPublishGreaterThan(String authorName, String yearOfPublish); 

This will create the query for you.

Read for about Query methods in the official documentation: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.