Mapping a row from a SQL data to a Java object

前端 未结 9 1185
悲哀的现实
悲哀的现实 2021-02-06 02:34

I have a Java class with instance fields (and matching setter methods) that match the column names of a SQL database table. I would like to elegantly fetch a row from the table

9条回答
  •  北荒
    北荒 (楼主)
    2021-02-06 03:03

    You can do it generically by doing the following simple methods:

    Interface to use as a method pointer:

    public interface I_DBtoJavaObjectConvertable
    {
        public T createFromDB(ResultSet i_rs) throws SQLException;
    }
    

    Generic class to handle every mapping from SQL to java Object:

    public class DBManager
    {
    
        static volatile Connection conn;
    
        //set here a static c'tor to handle the connection to the database
    
        //The General generic method:    
        public static  List GetObjectsFromDB(String i_Query, I_DBtoJavaObjectConvertable i_Converter)
        {
            List ResList = new ArrayList<>();
    
            try
            {
                Statement st = conn.createStatement();
                for (ResultSet rs = st.executeQuery(i_Query); rs.next();)
                {
                    ResList.add((T) i_Converter.createFromDB(rs));
                }
            }
            catch (SQLException ex)
            {
                _LOG_ERROR(ex.getMessage());
            }
    
            return ResList;
        }
    }
    

    Now By using Lanbda expression use can easlly convert an sql row to object, by given your convertion method, for example:

    public static User FetchUserFromDB(ResultSet i_rs)
    {
        User userToCreate = null;
        try
        {
            String FirstName = i_rs.getString("FirstName");
            String LastName = i_rs.getString("LastName");
            String Password = i_rs.getString("Password");
    
            userToCreate = new User(FirstName, LastName, Password);
    
        }
        catch (SQLException ex)
        {
            _LOG_ERROR("Error in fetching user from DB: \n" + ex.getMessage());
        }
        return userToCreate;
    }
    

    And now you can use this this method to bring any Users you want:

    public static List GetAllUsersFromDB() throws SQLException
    {
        String Query = "select * "
                + "from UsersTable";
    
        return DBManager.GetObjectsFromDB(Query, rs -> FetchUserFromDB(rs));
    }
    

    Or:

    public static List GetAllNamesFromDB() throws SQLException
    {
        String Query = "select FirstName "
                + "from UsersTable";
    
        return DBManager.GetObjectsFromDB(Query, rs -> rs.getString("FirstName"));
    }
    

提交回复
热议问题