JPA – Java Persistence API
This JAVA programming framework is part of EJB3.0 in JEE5. It is very powerful and removes a truckload of work for todays enterprise developer. You manage the relation between classes and relational DB’s via ORM. Once you digest the concept, it become part of your toolset.
I come from a old-fashioned background and always interest what runs under the hood and like to know about the manual way as well before indulging the “can-do-everything-easily” way.
So here my hommage to the “old” of directly accessing a DB. I am still using this approach for simple J2SE tools though ! I will talk about JPA more in detail soon.
Open and access a MySQL DB from Java
Establish a connection
String userName = “user”;
String password = “********”;
String url = “jdbc:mysql://localhost/db_sample”;
Class.forName(“com.mysql.jdbc.Driver”).newInstance();
con = (Connection) DriverManager.getConnection(url, userName, password);
Read from a table
Statement dbStatement = (Statement) con.createStatement();
ResultSet dbResultSet = dbStatement.executeQuery(“Select * from table_name”);
while (dbResultSet.next()) {
String testField = dbResultSet.getString(“fieldname”);
}
(Dont forget to cover both with try-catch’es and Netbeans will remind you of all the missing imports)
You see a number of potential flaws which gonna create trouble once you need to change it:
– hardcoded user, password, DB
– hardcoded table- and fieldnames
Imagine the project time 100 with dozens of tables and 100’s of fields, thats where the headache starts… You know what I am talking about.