问题描述
以下是负载示例:-
Stock stock = (Stock)session.load(Stock.class, new Integer(2));
StockTransaction stockTransactions = new StockTransaction();
//set stockTransactions detail
stockTransactions.setStock(stock);
session.save(stockTransactions);
如果我直接将id设置为:-
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);
因为我已经知道了库存表的ID.是调用负载还是获取?
As i already know the Id of the stock table. Y call the load or get?
推荐答案
您的第一个代码示例从数据库中获取对象,因此加载的对象将处于持久状态.您的第二个示例将尝试使用全新 Stock
保存StockTransaction
.这可能导致主键错误(如果库存编号是唯一的)或重复的条目.您应该根据自己的需求选择使用哪种方式.如果您需要现有的Stock
和StockTransaction
(我假设您是在写ID的情况下遇到这种情况)-您应该首先从数据库中加载它.
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.
Session.load()将返回一个带有空字段的代理,如果数据库中没有这样的对象(具有这样的ID).
Session.load() will return a proxy with empty fields, if there is no such object (with such id) in the database.
Session.get()如果没有具有该ID的对象,则将返回null.
Session.get() will return null if there is no object with such id.
使用哪个取决于您和您的任务.我个人更喜欢get()
.
Which one to use is up to you and your task. Personally I prefer get()
.
这篇关于Hibernate:直接在Bean中设置ID或调用load()或get()方法之间有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!