javaactivejdbcjavalite

JavaLite / ActiveJDBC: Derive database columns from Getters?


ActiveJDBC is a real "thin" database mapper allowing to query databases and mapping the results to POJOs. I'm using version 2.1-SNAPSHOT.

However, when it comes to the properties of a class, it looks like one has to do the hard work manually (or I've overseen an essential piece).

Example: Let's assume there is a class Person with firstName and lastName:

public class Person {
    private String firstName;
    private String lastName;

    public String getFirstName() {
       return this.firstName;
    }

    public void setFirstName(String f) {
       this.firstName = f;
    }

    // same for lastName
}

Retrieving now the data is easy:

List<Person> persons = Person.findAll();

However it seems it's necessary to assign the properties manually to a class:

for(Person p : persons) {
    System.out.println(p.getLastName()) // ===> null
}

So the question is: Is it possible (and if so, how) to access a POJO's properties using usual getters and setters? Or is it possible to annotate the fields to map them accordingly to the database columns (e.g. first_name, last_name)?

I need to access some fields of the POJO quite often and I'd like to use the standard getters to do so. However, accessing the Model's get(property) method is quite expensive (not sure if Model.get() implies a SELECT statement?).

Now I ended up with something ugly like

String getFirstName() {
  if (this.firstName != null) 
     return this.firstName;

  Object o = get("first_name");
   if (o == null) 
      this.firstName = "";
   else 
      this.firstName = o.toString;

   return  this.firstName;
}

So... have I missed anything here?... Appreciate any help.


Solution

  • Sorry, but your code examples with properties do not correlate with the framework features and documentation. Also, a POJO is a Plain Old Java Object, which is not necessarily the same as a Java Bean, but you are conflating the two. For more information on ActiveJDBC attributes, refer to Getters and Setters.

    Additionally, you can convert an ActiveJDBC model to a "bean", but you should think of them more like maps:

    public class Person  extends Model{
    
        public String getFirstName() {
           return getString("first_name");
        }
    
        public void setFirstName(String f) {
           set("first_name", f)
        }
    }