Tibin Tomy Tibin Tomy - 3 months ago 27
MySQL Question

Is that possible to retrieve data from different table using same function in spring JDBC?

This is my function to get all rows from table player.

public List<Player> getAllPlayer() {
String sql = "SELECT * FROM PLAYER";
List<Player> lstPlayers = getJdbcTemplate().query(
sql, new BeanPropertyRowMapper(Player.class)
return lstPlayers;

I want to get data from another table 'student' using this same function.
Is it possible to get data from both table using same function by changing the
above code something like below ?

public List<Object> getData(String TableName) {
String sql = "SELECT * FROM " + TableName;
List<Object> lstPlayers = getJdbcTemplate().query(
sql, new BeanPropertyRowMapper(Object.class)
return lstPlayers;


You could do something like the following

List<Player> players = getData(Player.class);
List<Student> students = getData(Student.class);

public List<T> getData(Class<T> clazz) {

    String sql = "SELECT * FROM " + clazz.getSimpleName();
    List<T> lstPlayers  = getJdbcTemplate().query(
            new BeanPropertyRowMapper(clazz));

    return lstPlayers;

However in real life there's not much advantage. It's not that common to want to load all the contents of a database table at once due to performance and other reasons, so this method won't be as helpful as you think.