jeudi 14 janvier 2021

Where to keep all SQL query strings in a Java application?

I have a lot of SQL query strings that are distributed throughout my application. These queries are used in different way such as Spring JdbcTemplate, EJB3 and so on…

Is there a best practice where to keep them all?

My initial thought was to put all of them to a class with different static methods as below.

public class QueryStringService {
    public static String selectAllCars() {
        String selectCars = " select * from car";
        return selectCars;
    }    
    
    public static String selectCar(String id) {
        String selectCar = " select * from car where id = ".concat(id);
        return selectCar;
    }
}

And use them as below anywhere it will be needed:

List<Car> cars= remote.retrieveCar(QueryStringService.selectAllCars());

or

Car car = jdbcTemplate.queryForObject(QueryStringService.selectCar("12345"), new CarMapper());

Aucun commentaire:

Enregistrer un commentaire