Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有一个数据,如果已经存在,我想保存或更新。所以 saveOrUpdate() 但前提是我知道主键。
在每个任务之前,我可以从数据库中调用 select 来找出 id,但是有更好的方法吗?
编辑:
基本上我有电视节目剧集的数据库表(1000 多个对象)。当我所谓的订购电视节目并想将例如 60 集添加到数据库时,我必须在插入每一集之前进行一次 if 检查(选择调用以接收主键)。听起来应该是这样吗?
如果您事先知道主键并且确定存在该 PK 的行,则可以 Session.get(Serializable id)使用Session.load(Serializable id); get()将创建所需类型的对象而不会访问数据库。 在其他情况下,你不能@Entity没有一个@Id(在 Hibernate 启动期间你会得到一个错误),因此如果你正在使用Session.saveOrUpdate(obj)你有obj主键,这是设计的。
Session.get(Serializable id)
Session.load(Serializable id)
get()
@Entity
@Id
Session.saveOrUpdate(obj)
obj