How to add multiline Strings in Java?

Tags: ,



How to make long queries more readable?

For example I have this one:

String query = "SELECT CASE WHEN EXISTS (SELECT * FROM users WHERE username = 'username' AND user_password = crypt('password', user_password)) THEN 'match' ELSE 'differ' END";

And it’s completely unreadable, are there any ways to beautify it?

Answer

Since Java 15, you can use text blocks:

String query = """
               SELECT CASE 
                  WHEN 
                      EXISTS (
                         SELECT * 
                         FROM users 
                         WHERE 
                             username = 'username' 
                             AND user_password = crypt('password', user_password)
                      ) 
                  THEN 'match' 
                  ELSE 'differ' 
                  END
                """;


Source: stackoverflow