Search code examples
javapostgresqlactivejdbc

How to retrieve the auto generated primary key in postgres with ActiveJDBC


in ActiveJDBC

If I have a serial primary key in the table with column name id

Employee e = new Employee();
        e.set("name", "John");
        e.set("age", 43);
        e.saveIt();

how is possible to retrieve it after saving the record? I want to retrieve in order to insert an address for that employee:

Address d = new Address();
     d.set("employee_id", ???); // what to do here?
     d.set("address", address);
     d.saveIt();

Solution

  • well, ActiveJDBC will do this automatically. Here is the same code that will properly set the ID:

    Employee e = Employee.createIt("name", "John", "age", 43);
    Address d = Address.create("address", address);    
    e.add(d);
    

    That was a short way of writing it. The longer version:

    Employee e = new Employee();
    e.set("name", "John", "age", 43).saveIt();
    Address d = new Address();
    d.set("address", address);
    e.add(d);
    

    In either case, you can get the Id from a model after you save like this:

    id = e.getId()
    

    For more information, refer: http://javalite.io/one_to_many_associations