Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add multiline Strings in Java?

Tags:

java

sql

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?

like image 996
vladzaba Avatar asked Sep 16 '25 15:09

vladzaba


2 Answers

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
                """;
like image 168
StandByUkraine Avatar answered Sep 19 '25 05:09

StandByUkraine


  1. In cases when you don't wont to blend SQL and JAVA you can put SQL queries in an .sql file. And get this text when needed.

    public class QueryUtil {
        static public String getQuery(String fileName) throws IOException {
            Path path = Paths.get("src/test/resources//" + fileName + ".sql");
            return Files.readAllLines(path).get(0);
        }
    }
    
  2. If you can mix SQL and JAVA then starting from JDK15 you can use text blocks for this.

  3. Also you can generates Java code from your database by using JOOQ, it gives many benefits.

like image 42
Eugen Avatar answered Sep 19 '25 05:09

Eugen