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

时间:2013-03-18 13:35:05

标签: 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 );

提前致谢。

3 个答案:

答案 0 :(得分: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);

它也在那里

答案 1 :(得分:2)

像Hibernate这样的ORM将Java对象映射到数据源并创建此数据的模型,然后创建和更新对象并调用save子例程来更新模型。插入/更新/删除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();

答案 2 :(得分:0)

只要您定义了适当的关系,您的代码就可以运行。 例如 - 如果您的StockCategory.java看起来像这样,那么您正在做的事情将起作用。

Class StockCategory{

     @ManyToOne(...)
     private Stock stock;

     @ManyToOne(...)
     private Category 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 );