tags:

views:

31

answers:

1

I was going to try using JDBC and an sqlite driver to save information into a file. It seems to work fine, but I was wondering if there was a more automated way to set it up. Maybe almost like a key-value pair.

Anyway, this is what I'm doing now...

Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db");
Statement stat = conn.createStatement();
stat.executeUpdate("drop table if exists people;");
stat.executeUpdate("create table people (name text, age int, etc...);");
PreparedStatement prep = conn.prepareStatement(
  "insert into people values (?, ?, etc... );");

for (int i = 0; i < persons.length; i++) {
   prep.setString(1, persons[i].name)
   prep.setString(2, persion[i].age)
   ....

   prep.addBatch()
}

conn.setAutoCommit(false);
prep.executeBatch();

The (?,?) is kind of hacky when there are like ten fields I want to store from the class, which may change later. Counting seems very old school.

Ideally, I'd just like to go through my class and annotate which fields I'd like to store (mostly primitives like ints), but if they're objects, get the fields they annotate. Either that or something that just sits on JDBC and has a slightly faster, cleaner syntax for building the table and adding objects. This doesn't have to be persistent. It's only for rare reads and writes.

A: 

Well, it sounds you're looking for JPA or Hibernate. These frameworks do exactly what you describe, annotate your fields and persist them in a database. There is a learning curve involved though, but it is well worth it.

Here is more info about JPA.

and here for hibernate.

These frameworks will allow mapping to an existing database or create the tables for you for new developments.

Note that these are not lightweight frameworks.

Peter Tillemans
After looking into JPA, I eventually found orbroker, which I think meets my needs well. Thanks.
voodoogiant
Great, thanks for the tip. I am going to look into this project, this looks cool. If you like to do your own SQL, you may also be interested in mybatis, which is a very mature OR framework where you own the SQL.
Peter Tillemans