How to add multiline Strings in Java?

Viewed 496

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?

5 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
                """;
  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.

Assuming that you can't move to a newer-than-8 version of Java (or even if you can), by far the best solution is to use an ORM. For Java it pretty much comes down to Hibernate, or jOOQ. jOOQ (and possibly Hibernate, I haven't used it so can't say, sorry) allows you to use a fluent programming interface, which is very much in keeping with existing Java code style and patterns.

Another specific advantage of using an ORM is that you can very easily change which DB engine you use without having to change the Java code that you've written beyond changing the SQL dialect in your setup functions. See https://www.jooq.org/javadoc/latest/org.jooq/org/jooq/SQLDialect.html.

You can use JOOQ and get multiple other benefits like type safety, auto-complete, easy mapping and great support.

Have used it for several projects so far and also competition like Kotlin Exposed but always came back to JOOQ.

Related