001
014
015 package com.liferay.portal.service.persistence;
016
017 import com.liferay.portal.kernel.dao.orm.ORMException;
018 import com.liferay.portal.kernel.dao.orm.Session;
019 import com.liferay.portal.kernel.util.InitialThreadLocal;
020 import com.liferay.portal.model.BaseModel;
021 import com.liferay.portal.util.PropsValues;
022
023
027 public class BatchSessionImpl implements BatchSession {
028
029 public boolean isEnabled() {
030 return _enabled.get();
031 }
032
033 public void setEnabled(boolean enabled) {
034 _enabled.set(enabled);
035 }
036
037 public void update(Session session, BaseModel<?> model, boolean merge)
038 throws ORMException {
039
040 if (merge || model.isCachedModel()) {
041 session.merge(model);
042 }
043 else {
044 if (model.isNew()) {
045 session.save(model);
046 }
047 else {
048 boolean contains = false;
049
050 if (isEnabled()) {
051 Object obj = session.get(
052 model.getClass(), model.getPrimaryKeyObj());
053
054 if ((obj != null) && obj.equals(model)) {
055 contains = true;
056 }
057 }
058
059 if (!contains && !session.contains(model)) {
060 session.saveOrUpdate(model);
061 }
062 }
063 }
064
065 if (!isEnabled()) {
066 session.flush();
067
068 return;
069 }
070
071 if ((PropsValues.HIBERNATE_JDBC_BATCH_SIZE == 0) ||
072 ((_counter.get() % PropsValues.HIBERNATE_JDBC_BATCH_SIZE) == 0)) {
073
074 session.flush();
075 session.clear();
076 }
077
078 _counter.set(_counter.get() + 1);
079 }
080
081 private static final long _INITIAL_COUNTER = 1;
082
083 private static ThreadLocal<Long> _counter = new InitialThreadLocal<Long>(
084 BatchSessionImpl.class + "._counter", _INITIAL_COUNTER);
085 private static ThreadLocal<Boolean> _enabled =
086 new InitialThreadLocal<Boolean>(
087 BatchSessionImpl.class + "._enabled", false);
088
089 }