'Is there a better way of writing native SQL query with EntityManager Java Spring Boot application?

My current code look like this. I am not using any ORM framework like Hibernate. I need to use this raw SQL query.

public List<String> getEndcodedKeyByLenderId(String lenderId) {
    Query q = (Query) entityManager.createNativeQuery("SELECT clients.encoded_key FROM `users`\n" +
            "LEFT JOIN clients on clients.`user_id` = users.id AND (clients.currency = 'EUR')\n" +
            "WHERE `users`.`user_type` = 'Lender' AND `users`.`id` = :user_id LIMIT 1;");
    q.setParameter("user_id", lenderId);
    List<String> results = q.getResultList();
    return results;
}

I don't like so many " and \n and + symbol.

Is there better way to approach for same result?



Solution 1:[1]

Java Text Blocks to the rescue! (aka multiline Strings.) This has been a feature in Java since Java 15.

Formatting SQL in Java code is the primary use case in our environment. Here's an example using your query:

 String query = """
  SELECT clients.encoded_key FROM users
  LEFT JOIN clients on clients.user_id = users.id AND (clients.currency = 'EUR')
  WHERE users.user_type = 'Lender' AND users.id = :user_id LIMIT 1
  """;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brice Roncace