0

hereからチュートリアルに従っていますが、理解できない部分があります。

4. 実行 – ケース1

    session.beginTransaction();
    在庫在庫 = new Stock();
    stock.setStockCode("7052");
    stock.setStockName("PADINI");
    Category category1 = new Category("消費者", "消費者企業");
    session.save(カテゴリ1);

    StockCategory stockCategory = 新しい StockCategory();
    stockCategory.setStock(株式);
    stockCategory.setCategory(カテゴリ1);
    stockCategory.setCreatedDate(新しい日付()); //余分な列
    stockCategory.setCreatedBy("システム"); //余分な列

    stock.getStockCategories().add(stockCategory);

    session.save(在庫);

    session.getTransaction().commit();

在庫とカテゴリ 1 の間の関連付けが作成されました。

    stockCategory.setStock(株式);
    stockCategory.setCategory(カテゴリ1);

では、なぜまだ必要なのか

stock.getStockCategories().add(stockCategory);

ありがとう!!

4

2 に答える 2

2

データベースを満足させるために絶対に必要というわけではありませんが、そうしないとオブジェクト グラフの一貫性が失われます。

したがって、たとえば、この操作の結果として在庫とそのカテゴリを返し、クライアント コード (UI) が在庫カテゴリを繰り返し処理してシステムの新しい状態を表示する場合、新しく作成された在庫はカテゴリなしで表示されます。 、これは間違っています。

于 2012-09-14T08:27:46.633 に答える
1

Strictly speaking the add is not necessary for hibernate to persist the objects. If you were to explicitly save the stock category then the relationship would be persisted. However you're only saving the stock object. Because of this the stock category needs to be in the collection so that hibernate can find it.

Notice the CascadeType.ALL on the categories collection. This means that on save, hibernate should look at the items in this collection and save them all. Because of this saving the stock is sufficient for hibernate to find and save the stock category and persist the relationship. If you did not add the item to the collection hibernate would not be able to find it so the relationship would not be saved unless you explicitly saved the StockCategory.

As mentioned in other answers, it's also generally considered good practice to keep the object graph consistent with the persistent state to avoid subtle bugs where what is populated is different at different times.

于 2012-09-14T08:30:53.257 に答える