CodeNewbie Community 🌱

Cover image for Using Advanced LIKE Expressions in Spring boot
Tristan
Tristan

Posted on • Edited on

Using Advanced LIKE Expressions in Spring boot

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode
  • 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)

Collapse
 
jacobvarney profile image
jacobvarney

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?

Collapse
 
theplebdev profile image
Tristan • Edited
  • I would actually not recommend my above code any more. I have had issues with it in production. Instead I changed to derived query method, documentation can be found here: docs.spring.io/spring-data/jpa/doc...
  • The solution is : List<BlogPost>findByTitleIgnoreCaseContaining(String title);
  • I can't remember the exact code that gave me issues but It was a bug with the LIKE %:title% statements
Collapse
 
theplebdev profile image
Tristan

Here is a link to my github with the code: github.com/thePlebDev/JavaLeetCode...