Hibernate:有了 save,为什么还需要 persist.doc
文本预览下载声明
save
1 /**
2 * Persist the given transient instance, first assigning a generated identifier. (Or
3 * using the current value of the identifier property if the ttassigned/tt
4 * generator is used.) This operation cascades to associated instances if the
5 * association is mapped with {@code cascade=save-update}
6 *
7 * @param object a transient instance of a persistent class
8 *
9 * @return the generated identifier
10 */
11 public Serializable save(Object object);
persist
1 /**
2 * Make a transient instance persistent. This operation cascades to associated
3 * instances if the association is mapped with {@code cascade=persist}
4 * p/
5 * The semantics of this method are defined by JSR-220.
6 *
7 * @param object a transient instance to be made persistent
8 */
9 public void persist(Object object);
解释
save 因为需要返回一个主键值,因此会立即执行 insert 语句,而 persist 在事务外部调用时则不会立即执行 insert 语句,在事务内调用还是会立即执行 insert 语句的。
看 persist 的注释会觉得其不会立即执行 insert 语句,为何 在事务内调用会立即执行 insert 语句,后面再分析。
测试
SessionHelper
1 package demo;
2
3 import org.hibernate.*;
4 import org.hibernate.cfg.*;
5
6 public final class SessionHelper {
7 private static SessionFactory factory;
8
9 public static void execute(SessionAction action) {
10 execute(action, false);
11 }
12
13 public static void execute(SessionAction action, boolean beforeTransaction) {
14 Session session = openSession();
15 try {
16 if (beforeTransaction) {
17 System.out.println(action);
18 action.action(session);
19 }
20
21 System.out.println(begin transaction);
22 session.beginTransaction();
23 if (!beforeTransaction) {
24 System.out.println(action);
25 action.action(session);
26 }
27
28 System.out.println(flush and commit);
29 session.flush();
显示全部