3

リレーションテーブルの株式カテゴリに行を挿入しようとしています。

私はこの例に従っています:http ://www.mkyong.com/hibernate/hibernate-many-to-many-example-join-table-extra-column-annotation/

これで、テーブル在庫とカテゴリのデータがすでにあります。

後で、株式とカテゴリを相互に関連付けたいと思います。

カスタムSQLクエリを記述せずにこれを行うにはどうすればよいですか?

このようにStockCategoryを追加できれば可能ですか?

Stock stock = new Stock();
stock.setStockId(1);
Category category = new Category();
category.setCategoryId(1);
StockCategory stockCategory = new StockCategory();

stockCategory.setStock(stock); //here you need to get the stock object by id 
stockCategory.setCategory(category1); //here you need to get the category1 object by id
stockCategory.setCreatedDate(new Date()); //extra column
stockCategory.setCreatedBy("system"); //extra column
session.save(stockCategory );

前もって感謝します。

4

3 に答える 3

6
StockCategory stockCategory = new StockCategory();

stockCategory.setStock(stock); //here you need to get the stock object by id
stockCategory.setCategory(category1); //here you need to get the category1 object by id
stockCategory.setCreatedDate(new Date()); //extra column
stockCategory.setCreatedBy("system"); //extra column
session.save(stock);

それもあります

于 2013-03-18T13:37:05.557 に答える
2

Hibernate のような ORM は、Java オブジェクトをデータソースにマップし、このデータのモデルを作成します。次に、オブジェクトを作成および更新し、save サブルーチンを呼び出してモデルを更新します。Insert/Update/Delete SQL コマンドは、ORM ライブラリによって実行されます。

したがって、新しいオブジェクトを作成する例では、データソースは session.save(stock)が呼び出されるまで更新されません。

   session.beginTransaction();

    Stock stock = new Stock();
    stock.setStockCode("7052");
    stock.setStockName("PADINI");

    //assume category id is 7
    Category category1 = (Category)session.get(Category.class, 7);

    StockCategory stockCategory = new StockCategory();
    stockCategory.setStock(stock);
    stockCategory.setCategory(category1);
    stockCategory.setCreatedDate(new Date()); //extra column
    stockCategory.setCreatedBy("system"); //extra column

    stock.getStockCategories().add(stockCategory);

    session.save(stock);

    session.getTransaction().commit();
于 2013-03-18T13:51:58.950 に答える
0

As long as you define appropriate relationships, your code will work. For example - if your StockCategory.java looks something like this, then what you are doing will work.

Class StockCategory{

     @ManyToOne(...)
     private Stock stock;

     @ManyToOne(...)
     private Category category;
}

Then the following code will work. You don't have to populate other fields in Stock and Category.

    Stock stock = new Stock();
    stock.setStockId(1);
    Category category = new Category();
    category.setCategoryId(1);
    StockCategory stockCategory = new StockCategory();

    stockCategory.setStock(stock); 
    stockCategory.setCategory(category1); 
    stockCategory.setCreatedDate(new Date()); //extra column
    stockCategory.setCreatedBy("system"); //extra column
    session.save(stockCategory );
于 2013-03-18T14:27:20.540 に答える