Introduction
- This series is about all things related to using Spring Boot for web development.
The problem
- I was facing this problem:
I have a BlogPost entity and I want to be able to query the BlogPost table in my database for any blog post containing a certain title
.
The solution
@Query(value = "SELECT * FROM blogPost WHERE blogPost.title LIKE %:title%",nativeQuery = true)
List<BlogPost> findBlogPostByTitle(@Param("title") String title);
The weird bug I encountered
- I was using the the 'LIKE' operator but I kept running into a weird bug where it would only return the first value matched and not all the values. It turns out that it was due to improper syntax when passing the parameter to the SQL query. So if you are having a similar problem, check the syntax of your SQL.
Updated Solution
I have had issues with the code above in production. So I have switched to derived query methods instead of native queries. Full documentation on derived query methods can be found HERE.
The code that I currently running in production is:
List<BlogPost>findByTitleIgnoreCaseContaining(String title);
- Spring then uses the name of the method to create the proper SQL statements.
Conclusion
- Thank you for taking the time out of your day to read this blog post of mine. If you have any questions or concerns please comment below or reach out to me on Twitter.
Top comments (3)
Hello Tristan!
I'm glad to hear you figured this out on your own. So we can compare, what was the original query that was giving you trouble?
derived query method
, documentation can be found here: docs.spring.io/spring-data/jpa/doc...List<BlogPost>findByTitleIgnoreCaseContaining(String title);
LIKE %:title%
statementsHere is a link to my github with the code: github.com/thePlebDev/JavaLeetCode...