
org.rapidoid.jpa.JPATool Maven / Gradle / Ivy
package org.rapidoid.jpa;
import org.rapidoid.RapidoidThing;
import org.rapidoid.annotation.Authors;
import org.rapidoid.annotation.Since;
import org.rapidoid.lambda.Lmbd;
import org.rapidoid.u.U;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.metamodel.EntityType;
import java.util.List;
import java.util.concurrent.Callable;
/*
* #%L
* rapidoid-jpa
* %%
* Copyright (C) 2014 - 2016 Nikolche Mihajlovski and contributors
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
@Authors("Nikolche Mihajlovski")
@Since("5.1.0")
@Named
public class JPATool extends RapidoidThing {
@PersistenceContext
private volatile EntityManager em;
private final boolean managed;
/**
* This constructor should be used only implicitly by the dependency injection libraries.
*/
public JPATool() {
this(null, true);
}
public JPATool(EntityManager em, boolean managed) {
this.em = em;
this.managed = managed;
}
public E save(E entity) {
Object id = getIdentifier(entity);
if (id == null) {
return insert(entity);
} else {
return update(entity);
}
}
public E insert(final E entity) {
return transactional(new Callable() {
@Override
public E call() throws Exception {
em.persist(entity);
return entity;
}
});
}
public E update(final E entity) {
return transactional(new Callable() {
@Override
public E call() throws Exception {
if (em.contains(entity)) {
em.persist(entity);
return entity;
} else {
return em.merge(entity);
}
}
});
}
public E merge(final E entity) {
return transactional(new Callable() {
@Override
public E call() throws Exception {
return em.merge(entity);
}
});
}
public void delete(final Class clazz, final Object id) {
transactional(new Callable() {
@Override
public E call() throws Exception {
em.remove(get(clazz, id));
return null;
}
});
}
public void delete(final Object entity) {
transactional(new Callable
© 2015 - 2025 Weber Informatics LLC | Privacy Policy