001/*******************************************************************************
002 * Copyright 2017 The MIT Internet Trust Consortium
003 *
004 * Portions copyright 2011-2013 The MITRE Corporation
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License");
007 * you may not use this file except in compliance with the License.
008 * 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 *******************************************************************************/
018package org.mitre.util.jpa;
019
020import java.util.List;
021
022import javax.persistence.EntityManager;
023import javax.persistence.TypedQuery;
024
025import org.mitre.data.PageCriteria;
026
027/**
028 * @author mfranklin
029 *         Date: 4/28/11
030 *         Time: 2:13 PM
031 */
032public class JpaUtil {
033        public static <T> T getSingleResult(List<T> list) {
034                switch(list.size()) {
035                        case 0:
036                                return null;
037                        case 1:
038                                return list.get(0);
039                        default:
040                                throw new IllegalStateException("Expected single result, got " + list.size());
041                }
042        }
043
044
045        /**
046         * Get a page of results from the specified TypedQuery
047         * by using the given PageCriteria to limit the query
048         * results. The PageCriteria will override any size or
049         * offset already specified on the query.
050         *
051         * @param <T>  the type parameter
052         * @param query the query
053         * @param pageCriteria the page criteria
054         * @return the list
055         */
056        public static <T> List<T> getResultPage(TypedQuery<T> query, PageCriteria pageCriteria){
057                query.setMaxResults(pageCriteria.getPageSize());
058                query.setFirstResult(pageCriteria.getPageNumber()*pageCriteria.getPageSize());
059
060                return query.getResultList();
061        }
062
063        public static <T, I> T saveOrUpdate(I id, EntityManager entityManager, T entity) {
064                T tmp = entityManager.merge(entity);
065                entityManager.flush();
066                return tmp;
067        }
068}