1

I want to create a query Select name from paitents where name [starts with a] using JDBC template. I have managed to create a query that selects everything as you can see from below.

public List<String> getAllUserNames() {
    List<String> usernameList = new ArrayList<>();
    usernameList.addAll(jdbcTemplate.queryForList("SELECT FirstName from paitents", String.class));
    return usernameList;
}
UkFLSUI
  • 5,509
  • 6
  • 32
  • 47
  • I think that is what you want: [link](https://stackoverflow.com/questions/11103797/how-to-search-string-like-something-with-java-spring-framework) – Sebastiano Grassi Feb 15 '22 at 17:09

2 Answers2

1

You can use the LIKE keyword for this.

Select name from paitents where name LIKE 'a%';

https://www.mysqltutorial.org/mysql-like/

user1738539
  • 874
  • 2
  • 11
  • 23
1

You can use the LIKE operator.

public List<String> getAllUserNames(String firstLetter) {
    List<String> usernameList = new ArrayList<>();
    usernameList.addAll(jdbcTemplate.queryForList(String.format("SELECT FirstName from patients where first_name LIKE %s%s", firstLetter, "%"), String.class));
    return usernameList;
}
graceja
  • 81
  • 5
  • How would I implement this when the 'firstLetter' is inputted from a form. Do I call the Query in my controller and put the variable containing the first letter in the bracket? e.g userRepo.getName(variable) – Joshcampbell7 Feb 15 '22 at 18:33
  • Generally, you would call the query from within a service. The service would be autowired into your controller. Just pass the variable into your getAllUserNames() method. I edited my answer to demonstrate. Also... you have a typo in your query. The patients table is misspelled as "paitents". Of course the answer is also not SQL Injection safe so always make sure you are following best practices to sanitize input if you are receiving it from a form. – graceja Feb 15 '22 at 19:48