SARJ - Simple Active Record for Java

Overview

This is a Java implementation of the Active Record pattern described by Martin Fowler. It is intended to be a light weight, easy to use system for accessing a database within Java programs.

This implementation requires Java 5 or above

Quick Start

  1. Download the latest SARJ jar file the download page
  2. Download the JDBC implementation for the database you're using (e.g. oracle.jar for Oracle, mysql-connector-java-5.1.5-bin.jar for MySQL)
  3. Create a file called connection.properties containing details for connecting to your database eg.
          driver-class=org.apache.derby.jdbc.EmbeddedDriver
          connection-string=jdbc:derby:active_record_test;create=true
          username=
          password=
            
  4. Create subclasses of ActiveRecord named after the database tables you're going to access eg.
          class Customer extends ActiveRecord
          {
          }
            
  5. Put all of these files on the classpath of your Java application
  6. From within your Java application you can now access your database using code like this,
          // Create
          Customer john = new Customer();
          john.set("NAME", "John");
          john.set("AGE", 25);
          john.save();
          Customer greg = new Customer();
          greg.set("NAME", "Greg");
          greg.set("AGE", 47);
          greg.save();
    
          // Read
          List<Customer> customers = ActiveRecord.find(Customer.class);
          for (Customer customer : customers)
          {
            System.out.println("Found customer - Name: " + customer.get("NAME") +
                ", age: " + customer.get("AGE"));
          }
    
          // Update
          john = ActiveRecord.find(Customer.class, "NAME = ?", "John").first();
          john.set("AGE", 26);
          john.save();
    
          // Delete
          customers = ActiveRecord.find(Customer.class);
          for (Customer customer : customers)
          {
            customer.delete();
          }
            
    For a full list of the operations available see the API documentation. For full code examples download a copy of the project and look in the examples directory.
  7. You're done, have an orange
SourceForge.net Logo