I don't want to make my code tight coupled to some JDBC driver (for example MySql). I want to make universal code, that can work with many database implementations. And I don't quite understand how to achieve this goal when using JDBC.
I think to achieve this I need only to export driver class name(and connection string) to .properties
file (for example "com.mysql.jdbc.Driver"
), and then in code use it like this Class.forName(PROPERTIES.getDriverName()).newInstance();
So when I decide to change my database, all what I need to change is jdbc driver name in .properties
file (for example to "COM.ibm.db2.jdbc.app.DB2Driver"
), connection string, and change driver's .jar
file in classpath.
Is it right?
Loose coupling can be achieved in several ways -
A. Use Hibernate , but this may be an overkill for your needs and hurt performance (if your application performs mostly write operation)
B. Use Spring-JDBC or any other framework that serves as JDBC wrapper - usually they provide some sort of abstraction
C. If your code is Java EE code, you can work with DataSources, and configure them on your Java application server - you will lookup the data source by name, and you will not know the implementation details behind
D. You can make sure you build the application in layers - a business logic layer, that uses a data access layer, which uses some data engine (Make sure your data engine class implement an interface you so u can change implementation easily).
Your Data engine class can read the information about the jdbc driver from a configuration (properties of XML files) - this is basically what Hibernate does , for example.