java - In activeJDBC, how to enforce the presence of a one-to-many relationship to a model -


assuming have following db model:

car(   id             int   plaque_id      int  )  plaque(   id             int   identification text ) 

so in activejdbc, models are:

public class car extends model {      static{         validatepresenceof("plaque_id");     }      public car () {} } 

..

public class plaque extends model {          static{             validatepresenceof("identification");         }          public car () {}     } 

assuming specification says: car must have plaque.

as can see, enforcing presence of plaque_id car model.

now. when try this:

car model_s = new car(); plaque plaque_a = new plaque();  plaque_a.set("identification","a-8000"); plaque_a.saveit();  car.add(plaque_a); car.saveit(); 

i got following exception thrown:

java.lang.illegalargumentexception: can add associated model instance exists in db. save instance first, able add dependencies it.

if understand correctly, car model_s must saved first before being able link plaque plaque_a. cannot save model_s without plaque due validation rule. it's catch-22.

note: new activejdbc.

i think got backwards. since table car has column plaque_id, means plaque has many car(s), one-to-many association: http://javalite.io/one_to_many_associations.

therefore, need add car plaque, , not other way around:

car model_s = new car();    // set parameters on car plaque_a.set("identification","a-8000"); plaque_a.saveit(); plaque_a.add(model_s);  

other recommendations:

1) in java, use camelcase: models, not model_s

2) add constructor plaque:

public class plaque{    public plaque(string identification){        set("identification", identification);    }    public plaque(){} // must have default constructor } 

then code cleaner:

car model_s = new car();    // set parameters on car plaque plaque = new plaque("a-8000"); plaque_a.saveit(); plaque_a.add(models);  

generally, try avoid dynamic setters , getters, ok small project, writing permanent setters , getters amazing power of java refactoring, not have in ruby.


Comments

Popular posts from this blog

How to understand 2 main() functions after using uftrace to profile the C++ program? -

c# - Update a combobox from a presenter (MVP) -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -