Thursday 27th October 2016

Cruddy

Cruddy is a very simple and lightweight database abstraction layer for those who are tired of the bloated alternatives like hibernate.

When I connect to the database, I don't want to be forced to use a half-baked SQL impersonator like HQL. SQL is good, SQL is right, it does the job and is purpose built for the task of querying your database. Why reinvent this?

I've heard people claim that it provides database portability, but the few times in my career where I've had to move from one database vendor to another mid-project, Hibernate and it's ilk have not helped because inevitably in large projects custom queries are required somewhere down the line and some long-gone developer bypassed Hibernate and HQL because it either didn't work, was too hard or he didn't know enough work within it.

Anyway, I digress... cruddy provides a refreshingly simple alternative that will get out of your way if you want it to or hold your hand for simple create, update and delete operations.

You can get a copy of the latest (that's also the first, so beware bugs until I stabilise this a bit more) JAR file for the project here.

Examples

Initialising the connection pool

   // This sets up your database connection so that the 
   // library knows the right username and password to use
   ConnectionBroker.init("jdbc:postgresql:testdb", "testuser", "secretmagicword");

Fetching a list of objects from the database

   // This fetches a recordset from the DB and fills a List with a POJO of your 
   // choosing
   try (Database db = Database.connect()) {
      String sql = "select * from test";
      List<TestRecord> list = db.query(TestRecord.class, sql);
   } catch (SQLException e) {
      LOG.log(Level.SEVERE, e.toString());
   }

Saving an object to the database

   // You can also work with single POJOs in handy ways like...
   try (Database db = Database.connect()) {

      TestRecord t = new TestRecord();
      t.setData("some data");
      t.setNumericStuff(32);

      db.insert(t);

      t.setData("some changed data");

      db.update(t);

   } catch (SQLException e) {
      LOG.log(Level.SEVERE, e.toString());
   }

Arbitrary SQL execution

   try (Database db = Database.connect()) {

      String sql = "update customer set field1 = 'some data' where somekey = 123";
      int rowsChanged = 0;

      rowsChanged = db.execute(sql);

      LOG.log(Level.INFO, rowsChanged + " rows updated");


   } catch (SQLException e) {
      LOG.log(Level.SEVERE, e.toString());
   }