我正在尝试将一行插入到关系表Stock Category.
我遵循这个例子:http://www.mkyong.com/hibernate/hibernate-many-to-many-example-join-table-extra-column-annotation/
现在我已经有了表stock和category中的数据。
稍后我想将股票和类别相互关联。
我怎么能做到这一点,而不写一个自定义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 );
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);
像Hibernate这样的ORM将Java对象映射到数据源并创建该数据的模型,然后创建和更新对象并调用save子例程来更新模型。SQL的Insert/Update/Delete命令由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();
只要您定义了适当的关系,您的代码就可以工作。例如,如果您的StockCategory.java看起来像这样,那么您所做的将会工作。
Class StockCategory{
@ManyToOne(...)
private Stock stock;
@ManyToOne(...)
private Category category;
}
那么下面的代码将工作。您不必在Stock和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 );