如何使用hibernate方法插入一行?

Thi*_*ker 3 java hibernate hibernate-mapping hibernate-annotations

我试图在关系表股票类别中插入一行.

我跟随这个例子: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 );
Run Code Online (Sandbox Code Playgroud)

提前致谢.

PSR*_*PSR 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);
Run Code Online (Sandbox Code Playgroud)

它也在那里