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 019package org.apache.oozie.executor.jpa; 020 021import java.util.List; 022import javax.persistence.EntityManager; 023import javax.persistence.PersistenceException; 024import javax.persistence.Query; 025 026import org.apache.oozie.ErrorCode; 027import org.apache.oozie.client.rest.JsonBean; 028import org.apache.oozie.service.JPAService; 029import org.apache.oozie.service.Services; 030import org.apache.oozie.util.XLog; 031 032/** 033 * Base Class of Query Executor 034 */ 035public abstract class QueryExecutor<T, E extends Enum<E>> { 036 private static XLog LOG; 037 038 protected QueryExecutor() { 039 } 040 041 public abstract int executeUpdate(E namedQuery, T jobBean) throws JPAExecutorException; 042 043 public void insert(JsonBean bean) throws JPAExecutorException { 044 if (bean != null) { 045 JPAService jpaService = Services.get().get(JPAService.class); 046 EntityManager em = jpaService.getEntityManager(); 047 try { 048 em.getTransaction().begin(); 049 em.persist(bean); 050 em.getTransaction().commit(); 051 } 052 catch (PersistenceException e) { 053 throw new JPAExecutorException(ErrorCode.E0603, e); 054 } 055 finally { 056 if (em.getTransaction().isActive()) { 057 LOG.warn("insert ended with an active transaction, rolling back"); 058 em.getTransaction().rollback(); 059 } 060 if (em.isOpen()) { 061 em.close(); 062 } 063 } 064 } 065 } 066 067 public abstract T get(E namedQuery, Object... parameters) throws JPAExecutorException; 068 069 public abstract List<T> getList(E namedQuery, Object... parameters) throws JPAExecutorException; 070 071 public abstract Query getUpdateQuery(E namedQuery, T wfBean, EntityManager em) throws JPAExecutorException; 072 073 public abstract Query getSelectQuery(E namedQuery, EntityManager em, Object... parameters) 074 throws JPAExecutorException; 075 076 public abstract Object getSingleValue(E namedQuery, Object... parameters) 077 throws JPAExecutorException; 078 079}