3

我正在尝试在关系表 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 );

提前致谢。

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 对象映射到数据源并创建此数据的模型,然后创建和更新对象并调用保存子例程来更新模型。插入/更新/删除 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

只要您定义了适当的关系,您的代码就可以工作。例如 - 如果您的 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 );
于 2013-03-18T14:27:20.540 回答