001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements. See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership. The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License. You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018 package org.apache.oozie.executor.jpa;
019
020 import java.util.List;
021 import javax.persistence.EntityManager;
022 import javax.persistence.PersistenceException;
023 import javax.persistence.Query;
024
025 import org.apache.oozie.ErrorCode;
026 import org.apache.oozie.client.rest.JsonBean;
027 import org.apache.oozie.service.JPAService;
028 import org.apache.oozie.service.Services;
029 import org.apache.oozie.util.XLog;
030
031 /**
032 * Base Class of Query Executor
033 */
034 public abstract class QueryExecutor<T, E extends Enum<E>> {
035 private static XLog LOG;
036
037 protected QueryExecutor() {
038 }
039
040 public abstract int executeUpdate(E namedQuery, T jobBean) throws JPAExecutorException;
041
042 public void insert(JsonBean bean) throws JPAExecutorException {
043 if (bean != null) {
044 JPAService jpaService = Services.get().get(JPAService.class);
045 EntityManager em = jpaService.getEntityManager();
046 try {
047 em.getTransaction().begin();
048 em.persist(bean);
049 em.getTransaction().commit();
050 }
051 catch (PersistenceException e) {
052 throw new JPAExecutorException(ErrorCode.E0603, e);
053 }
054 finally {
055 if (em.getTransaction().isActive()) {
056 LOG.warn("insert ended with an active transaction, rolling back");
057 em.getTransaction().rollback();
058 }
059 if (em.isOpen()) {
060 em.close();
061 }
062 }
063 }
064 }
065
066 public abstract T get(E namedQuery, Object... parameters) throws JPAExecutorException;
067
068 public abstract List<T> getList(E namedQuery, Object... parameters) throws JPAExecutorException;
069
070 public abstract Query getUpdateQuery(E namedQuery, T wfBean, EntityManager em) throws JPAExecutorException;
071
072 public abstract Query getSelectQuery(E namedQuery, EntityManager em, Object... parameters)
073 throws JPAExecutorException;
074
075 public abstract Object getSingleValue(E namedQuery, Object... parameters)
076 throws JPAExecutorException;
077
078 }