1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * The contents of this file are subject to the terms of the Liferay Enterprise
5    * Subscription License ("License"). You may not use this file except in
6    * compliance with the License. You can obtain a copy of the License by
7    * contacting Liferay, Inc. See the License for the specific language governing
8    * permissions and limitations under the License, including but not limited to
9    * distribution rights of the Software.
10   *
11   *
12   * 
13   */
14  
15  package com.liferay.portal.service.persistence;
16  
17  import com.liferay.portal.kernel.dao.orm.ORMException;
18  import com.liferay.portal.kernel.dao.orm.Session;
19  import com.liferay.portal.kernel.util.InitialThreadLocal;
20  import com.liferay.portal.model.BaseModel;
21  import com.liferay.portal.util.PropsValues;
22  
23  /**
24   * <a href="BatchSessionImpl.java.html"><b><i>View Source</i></b></a>
25   *
26   * @author Raymond Augé
27   * @author Brian Wing Shun Chan
28   */
29  public class BatchSessionImpl implements BatchSession {
30  
31      public boolean isEnabled() {
32          return _enabled.get();
33      }
34  
35      public void setEnabled(boolean enabled) {
36          _enabled.set(enabled);
37      }
38  
39      public void update(Session session, BaseModel<?> model, boolean merge)
40          throws ORMException {
41  
42          if (merge || model.isCachedModel()) {
43              session.merge(model);
44          }
45          else {
46              boolean contains = false;
47  
48              if (isEnabled()) {
49                  Object obj = session.get(
50                      model.getClass(), model.getPrimaryKeyObj());
51  
52                  if ((obj != null) && obj.equals(model)) {
53                      contains = true;
54                  }
55              }
56  
57              if (model.isNew()) {
58                  session.save(model);
59              }
60              else if (!contains && !session.contains(model)) {
61                  session.saveOrUpdate(model);
62              }
63          }
64  
65          if (!isEnabled()) {
66              session.flush();
67  
68              return;
69          }
70  
71          if ((PropsValues.HIBERNATE_JDBC_BATCH_SIZE == 0) ||
72              ((_counter.get() % PropsValues.HIBERNATE_JDBC_BATCH_SIZE) == 0)) {
73  
74              session.flush();
75              session.clear();
76          }
77  
78          _counter.set(_counter.get() + 1);
79      }
80  
81      private static final Long _INITIAL_COUNTER = new Long(1);
82  
83      private static ThreadLocal<Long> _counter =
84          new InitialThreadLocal<Long>(_INITIAL_COUNTER);
85      private static ThreadLocal<Boolean> _enabled =
86          new InitialThreadLocal<Boolean>(Boolean.FALSE);
87  
88  }