Work with ugly SQL in Java

This raises the question of SQL-Java coding style ...

How do others relate to creating complex custom queries in Java?

I am talking about a seemingly simple task of preparing a string, which is an SQL operation being performed.

I know HQL as well as stored procedures, but to be honest, I really don't like these solutions. Perhaps you can convince me differently. Stored procedures are annoying to deploy / maintain, and parsing performance is not such a big issue in my case - flexibility takes precedence. HQL seems like a big leap and has some limitations for my complex queries.

To be clear, I'm talking about a super-ugly looking code like this:

    return 
        "(" + topTwenty + ")" +
        "UNION " +
        "(" + twentyBeforeMe + ")" +
        "UNION " +
        "(" + meDummyQuery + ")" +
        "UNION " +
        "(" + twentyAfterMe + ")";

topTwenty , , , .

, , PHP, .

? ? ( -).

0
6

String.format , , (NamedPreparedStament), .

String sql = "SELECT id FROM %s WHERE id > :lastInsertedYesterday ";
NamedParameterStatement p = new NamedParameterStatement(con, 
                                    String.format(sql, "table1"));
p.setInt("lastInsertedYesterday", lastOne);
+1
+6

, , JDBC PreparedStatement s. PHP, PDO. . $variable PHP, , ? . ? ( ) PreparedStatement.

. Sun PreparedStatement .

+3

Java PrintFormat, sprintf C, .

The following code snippet is taken from http://java.sun.com/developer/technicalArticles/Programming/sprintf/

System.out.println(
new PrintfFormat("Pre %s Post%%").sprintf("target")
);  
+2
source

SQL Construction Set , this is my project, by the way.

+1
source

You can try using StringBuilder.append () if you think it will make your code cleaner:

return new StringBuilder()
   .append("(").append(topTwenty).append(")")
   .toString();
-1
source

All Articles