80 lines
2.2 KiB
Java
80 lines
2.2 KiB
Java
package dao;
|
|
|
|
|
|
import java.io.Serializable;
|
|
import java.lang.reflect.ParameterizedType;
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
|
|
import javax.annotation.PostConstruct;
|
|
import javax.persistence.EntityManager;
|
|
import javax.persistence.PersistenceContext;
|
|
import javax.persistence.PersistenceUnitUtil;
|
|
|
|
import org.springframework.transaction.annotation.Transactional;
|
|
|
|
public abstract class JpaDao<T, PK extends Serializable> implements Dao<T, PK> {
|
|
protected Class<T> entityClass;
|
|
|
|
// protected static EntityManagerFactory entityManagerFactory = null;
|
|
|
|
@PersistenceContext
|
|
protected EntityManager entityManager;
|
|
|
|
protected PersistenceUnitUtil persistenceUnitUtil;
|
|
|
|
// public static void setEntityManagerFactory(EntityManagerFactory factory)
|
|
// {
|
|
// entityManagerFactory = factory;
|
|
// }
|
|
|
|
public JpaDao() {
|
|
ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
|
|
this.entityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[0];
|
|
// entityManager = entityManagerFactory.createEntityManager();
|
|
}
|
|
|
|
@PostConstruct
|
|
private void initPersistenceUnitUtil() {
|
|
this.persistenceUnitUtil = entityManager.getEntityManagerFactory().getPersistenceUnitUtil();
|
|
}
|
|
|
|
@Transactional
|
|
public T create(T t) {
|
|
entityManager.persist(t);
|
|
return t;
|
|
}
|
|
|
|
@Transactional(readOnly = true)
|
|
public T read(PK id) {
|
|
return entityManager.find(entityClass, id);
|
|
}
|
|
|
|
@Transactional
|
|
public T update(T t) {
|
|
return entityManager.merge(t);
|
|
}
|
|
|
|
@Transactional
|
|
public void delete(T t) {
|
|
t = entityManager.merge(t);
|
|
entityManager.remove(t);
|
|
}
|
|
|
|
public List<T> getAll() {
|
|
List<T> result = entityManager.createQuery("from " + entityClass.getSimpleName(), entityClass).getResultList();
|
|
return result == null ? new ArrayList<T>() : result;
|
|
}
|
|
|
|
public long count() {
|
|
return ((Number) entityManager.createQuery("select count(e) from " + entityClass.getSimpleName() + " e").getSingleResult()).longValue();
|
|
}
|
|
|
|
public boolean isLoaded(T t) {
|
|
return persistenceUnitUtil.isLoaded(t);
|
|
}
|
|
|
|
protected boolean isFieldLoaded(T t, String fieldName) {
|
|
return persistenceUnitUtil.isLoaded(t, fieldName);
|
|
}
|
|
} |