通常,我通过 sql/hql 语句插入或更新对象来将对象存储在数据库中。
query = session.createQuery("INSERT INTO Employee(firstName, lastName, salary)");
query.executeUpdate();
最近我读到了 Hibernates session.save()
方法,它接受一个类,并且似乎自动执行将类及其属性插入数据库的魔法。
所以我想知道,“保存”有什么作用?
它只是为用户生成一条 SQL 语句吗?
或者说与普通的hqlQuery方式相比有什么优点或缺点?
最佳答案
保存:
Save 方法将对象存储到数据库中。它将持久保存给定的 transient 实例,首先分配生成的标识符。它返回创建的实体的 ID。
如docs
说,
Persist the given transient instance, first assigning a generated identifier. (Or using the current value of the identifier property if the assigned generator is used.) This operation cascades to associated instances if the association is mapped with cascade="save-update".
另请查看What are the differences between the different saving methods in Hibernate?
关于java - Hibernate保存和SQL插入有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26843776/