You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
argos/dmp-backend/data/src/main/java/eu/eudat/data/dao/databaselayer/context/DatabaseContext.java

51 lines
1.6 KiB
Java

package eu.eudat.data.dao.databaselayer.context;
import eu.eudat.queryable.QueryableList;
import eu.eudat.queryable.jpa.hibernatequeryablelist.QueryableHibernateList;
import eu.eudat.queryable.queryableentity.DataEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
@Repository("databaseCtx")
public class DatabaseContext<T extends DataEntity> {
@PersistenceContext
private EntityManager entityManager;
@Autowired
public DatabaseContext(EntityManagerFactory entityManagerFactory) {
this.entityManager = entityManagerFactory.createEntityManager();
}
public QueryableList<T> getQueryable(Class<T> type) {
return new QueryableHibernateList<>(this.entityManager, type).setEntity(type);
}
@Transactional
public T createOrUpdate(T item, Class<T> type) {
EntityManager entityManager = this.entityManager;
if (item.getKeys() != null) {
T oldItem = entityManager.find(type, item.getKeys());
if (oldItem != null) {
oldItem.update(item);
entityManager.merge(oldItem);
return oldItem;
} else {
entityManager.persist(item);
}
} else entityManager.persist(item);
return item;
}
public void delete(T item) {
this.entityManager.remove(item);
}
}