How can i insert a row using hibernate method?

Thinker picture Thinker · Mar 18, 2013 · Viewed 26.4k times · Source

I am trying to insert a row into a relation table Stock Category.

I am following this example: http://www.mkyong.com/hibernate/hibernate-many-to-many-example-join-table-extra-column-annotation/

Now I already have data in table stock and category.

Later I want to associate a stock and category to each other.

How I can do this without writing a custom sql query?

Is it possible if I can add StockCategory like this?

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 );

Thanks in advance.

Answer

PSR picture PSR · Mar 18, 2013
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);

It is also there