簡體   English   中英

在activeJDBC中,如何強制與模型建立一對多關系

[英]In activeJDBC, how to enforce the presence of a one-to-many relationship to a model

假設我具有以下數據庫模型:

Car(
  id             INT
  plaque_id      INT

)

Plaque(
  id             INT
  identification TEXT
)

因此,在ActiveJDBC中,我的模型是:

public class Car extends Model {

    static{
        validatePresenceOf("plaque_id");
    }

    public Car () {}
}

..

public class Plaque extends Model {

        static{
            validatePresenceOf("identification");
        }

        public Car () {}
    }

假設我的規范說:汽車必須有一塊牌子。

如您所見,我正在將plaque_id強制存在於Car模型中。

現在。 當我嘗試這個:

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();

我拋出了以下異常:

java.lang.IllegalArgumentException:您只能將關聯的模型添加到DB中存在的實例。 首先保存該實例,然后就可以向其添加依賴項。

如果我理解正確, 必須先保存我的汽車model_s,然后才能鏈接斑塊plaque_a 但是由於我的驗證規則,我無法保存沒有斑塊的model_s 這是一個陷阱22。

注意:我是activeJDBC的新手。

我想你把它弄倒了。 由於您的表Car有一列plaque_id ,這意味着Plaque有許多Car ,這是一對多關聯: http : //javalite.io/one_to_many_associations

因此,您需要將Car添加到Plaque ,而不是相反的方式:

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

其他建議:

1)在Java中,使用CamelCase: modelS ,而不是model_s

2)將構造函數添加到Plaque

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

那么您的代碼看起來會更干凈:

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

通常,盡量避免使用動態的setter和getter,對於一個小型項目來說,它們是可以的,但是編寫永久的setter和getter將為您提供Java重構的強大功能,而這在Ruby中是沒有的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM