Q:

Hibernate:Difference between setting the Id directly in the bean or calling the load() or get() method?

Following is an example of load:-
Stock stock = (Stock)session.load(Stock.class, new Integer(2));
           StockTransaction stockTransactions = new StockTransaction();
           //set stockTransactions detail
           stockTransactions.setStock(stock);        
           session.save(stockTransactions);

What is the difference if i directely set the id in like:-
Stock stock =new Stock();
stock.setId(2);
 StockTransaction stockTransactions = new StockTransaction();
               //set stockTransactions detail
               stockTransactions.setStock(stock);        
               session.save(stockTransactions);

As i already know the Id of the stock table. Y call the load or get?

A:

What is the difference ...

Your first sample of code fetches object from database, thus loaded object will be in persisted state. Your second sample will try to save StockTransaction with completely new Stock. This may lead to primary key errors (if stock id is unique) or duplicate entries. You should base the choice of which way to use on your requirements. If you need StockTransaction with existing Stock (I assume this is your case as you wrote that you know ID) - you should load it from database first.

Y call the load or get?

Session.load() will return a proxy with empty fields, if there is no such object (with such id) in the database.
Session.get() will return null if there is no object with such id.
Which one to use is up to you and your task. Personally I prefer get().

