Hibernate:直接在Bean中设置ID或调用load()或get()方法之间有区别吗? [英] Hibernate:Difference between setting the Id directly in the bean or calling the load() or get() method?

查看:110
本文介绍了Hibernate:直接在Bean中设置ID或调用load()或get()方法之间有区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是负载示例:-

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?

推荐答案

有什么区别...

What is the difference ...

您的第一个代码示例从数据库中获取对象,因此加载的对象将处于持久状态.您的第二个示例将尝试使用全新 Stock保存StockTransaction.这可能导致主键错误(如果库存编号是唯一的)或重复的条目.您应该根据自己的需求选择使用哪种方式.如果您需要现有的StockStockTransaction(我假设您是在写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.

您是要调用负载还是获取?

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.

使用哪个取决于您和您的任务.我个人更喜欢get().

Which one to use is up to you and your task. Personally I prefer get().

这篇关于Hibernate:直接在Bean中设置ID或调用load()或get()方法之间有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆