Using static final Strings for SQL Query in Spring Boot This is regarding code quality and coding standards with respect to Spring Ecosystem. Here there are two methods:


isRecordExists is using a class level static constant String query. (Definitely suggestable for old way where we use prepared statements)
isRecordExists2 is using method level String query


Which method is better (isRecordExists or isRecordExists2) in context with  Spring Boot?

@Repository
public class SpringRepository { 

    @Autowired
    private NamedParameterJdbcTemplate namedParamJdbcTemplate;

    private static final String QUERY = " select * from Dual where created_date=:date";

    public void isRecordExists(Date date){
       /**
       *  using constant for sql Query String at class level
       */
         MapSqlParameterSource parameters = new MapSqlParameterSource();
         parameters.addValue("date", date);
         namedParameterJdbcTemplate.queryForObject(QUERY, parameters, Integer.class);

    }
   public void isRecordExists2(Date date){
         String sqlQuery=" select * from Dual where created_date=:date";
       /**
       *  using  sql Query at method level
       */
         MapSqlParameterSource parameters = new MapSqlParameterSource();
         parameters.addValue("date", date);
         namedParameterJdbcTemplate.queryForObject(sqlQuery, parameters, Integer.class);

    }
Sorry to present the antithesis to an existing answer once more: if the string is neither reusable nor public, a constant makes no sense in my book. (And yes, this question is opinion-based ;-))

I see why you use a string-variable inside the medthod (to keep it readable for longer strings) which I find totally OK.

In general: aim to write the code for the audience of developers who come after you. In my experience, this future developer will dig through your code with a debugger because something goes wrong. Thus, he will not read the class in its entirity because he's curious, he will jump into that specific method from a stacktrace. All information that is locally there will be beneficial, as there is less jumping around in the code.