在Hibernate中使用另一个引用的实体插入/更新一个实体 [英] Inserting/Updating an entity with another referenced entities in Hibernate

查看:54
本文介绍了在Hibernate中使用另一个引用的实体插入/更新一个实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在休眠状态下插入/更新实体并只想更新对更新实体的更改时,可以只设置外键持有参考实体的ID吗?例如.

When inserting/updating an entity in hibernate and want to update changes only to the updating entity, is it ok to just set the ID of the foreign key holding reference entity? eg.

UserRole userRole = new UserRole();
userRole.setId(1);
User user = new User();
user.setUserRole(userRole);

userDao.update(user);
-OR-
userDao.insert(user);

还是我每次都需要从数据库获取完整引用的实体?例如.

Or do I need to get full referenced entity from database everytime? eg.

UserRole userRole = userRoleDao.getById(1);
User user = new User();
user.setUserRole(userRole);

userDao.update(user);
-OR-
userDao.insert(user);

两者对我来说似乎都很好.但是,恐怕第二种方法会对性能产生影响,第一种方法看起来像是不良代码.

Both seems to work fine for me. But I'm afraid there'll be performance impact on second approach and the first one looks like bad code.

推荐答案

如果idUserRole的主键,则两者都是正确的.

Both are correct if id is the primary key of the UserRole.

  • 我更喜欢第一种方法.

当一个实体先前被持久化后,您只需要主键来引用已经创建的实体.在数据库中也会发生这种情况,如果您查看User表,您将找不到完整的UserRole,而只会找到主键.

When an entity has been previously persisted you only need the primary key to reference already created entities. This happens also in the database, if you take a look at User table, you won't find a complete UserRole, you will just find the primary key.

但是我担心第二种方法会影响性能

But I'm afraid there'll be performance impact on second approach

所有操作都取决于数据库的位置,如果不执行此操作数百万次,则对性能的影响可以忽略不计,但是如果远程数据库和连接断开,则可以增加时间.

All depends where the database is, impact in performance will be negligible if you don't make this operation million of times, but time can be increased if remote database AND bad connection.

这篇关于在Hibernate中使用另一个引用的实体插入/更新一个实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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