How To Provide Database Independency in JDBC Without Using Hibernate.?

后端 未结 3 1327
小鲜肉
小鲜肉 2020-12-06 16:18

I am trying to solve this problem with the help of properties file, but in a Properties file, we can handle only Database Driver problem. If I want to switch my MySQL to Ora

相关标签:
3条回答
  • 2020-12-06 16:36

    You can write a generic method that can handle any sql query (regardless of the database used). The trick here is to use database metadata to automatically populate a hash map (a hash map is convenient because we can use the column names as keys) containing the query results. For parameterized queries, you'll need a more complex method, which can be found at the link provided below (DBSelect.getRecordsForCustomQuery). If all your queries targeting different databases are the same, then you don't even have to use metadata, just hardcode the column names.

    public Map<String, Object> getQueryResults(String query, Connection conn){
    
        ResultSet rs=null; 
        PreparedStatement stmt=null; 
        Map<String, Object> objMap = new HashMap<>();
    
        stmt = conn.prepareStatement(sqlQuery); 
        rs = stmt.executeQuery();
        while(rs.next()){
        for (int i=1;i<=rs.getMetaData().getColumnCount();i++) { 
                    objMap.put( rs.getMetaData().getColumnName(i), rs.getObject(i)); 
        }
     }
        return mapObj;
    
    }
    

    You can, of course, modify this method to suit your needs.

    A slightly more elaborate solution which uses reflection and generics can be found here ( https://github.com/IvanGH2/EasyORM ) but you don't even have to use all of that.

    0 讨论(0)
  • 2020-12-06 16:39

    I don't think so if you switch to hibernate or any orm frameworks. In case of hibernate you can use hql to write the queries in that way you are database independent no matter what database you switch hibernate will take care. You can even look at Spring CrudRepository. I highly doubtful you can achieve database independent queries just with the JDBC. It is good to begin with JDBC for a long run you should consider orm frameworks.

    0 讨论(0)
  • 2020-12-06 16:46

    If i want to switch my mysql to oracle database i need to change my all query.

    If your SQL queries rely only on the ANSI SQL and never on proprietary specificites (function, keywords, and...) you should be able to switch from an DBMS to another one without any change in the queries.
    Note that Hibernate will not translate for a DBMS specifities to another one as for example translate a query on the DUAL table written in Oracle to a MySQL way.
    Hibernate ensures that your SQL queries be portable while you don't create native queries, a possibility still provided by Hibernate.

    Here is the original SQL ANSI draft and here a download link for the last version of Information technology -- Database languages -- SQL -- Part 1: Framework (SQL/Framework)

    0 讨论(0)
提交回复
热议问题