0

Assuming I have the following DB model:

Car(
  id             INT
  plaque_id      INT

)

Plaque(
  id             INT
  identification TEXT
)

So in ActiveJDBC, my models are:

public class Car extends Model {

    static{
        validatePresenceOf("plaque_id");
    }

    public Car () {}
}

..

public class Plaque extends Model {

        static{
            validatePresenceOf("identification");
        }

        public Car () {}
    }

Assuming my specification says: a car must have a plaque.

As you can see, I am enforcing the presence of plaque_id to the Car model.

Now. When I 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 the following exception thrown:

java.lang.IllegalArgumentException: You can only add associated model to an instance that exists in DB. Save this instance first, then you will be able to add dependencies to it.

If I understand correctly, my car model_s must be saved first before being able to link plaque plaque_a. But I cannot save model_s without a plaque due to my validation rule. It's a catch-22.

Note: I am new to activeJDBC.

TGI
  • 559
  • 1
  • 6
  • 15

1 Answers1

0

I think you got it backwards. Since your table Car has a column plaque_id, it means that a Plaque has many Car(s), which is a One-to-Many association: http://javalite.io/one_to_many_associations.

Therefore, you need to add Car to Plaque, and not the other way around:

Car model_s = new Car();    // set parameters on the 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 to Plaque:

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

then your code will look cleaner:

Car model_s = new Car();    // set parameters on the car
Plaque plaque = new Plaque("A-8000");
plaque_a.saveIt();
plaque_a.add(modelS); 

Generally, try to avoid dynamic setters and getters, they are OK for a small project, but writing permanent setters and getters will get you an amazing power of Java refactoring, something you do not have in Ruby.

ipolevoy
  • 5,432
  • 2
  • 31
  • 46