1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
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  }