2018-03-21 11:57:56 +01:00
|
|
|
package eu.eudat.data.dao.databaselayer.context;
|
2017-12-17 22:34:24 +01:00
|
|
|
|
|
|
|
import eu.eudat.queryable.QueryableList;
|
2018-05-28 11:50:42 +02:00
|
|
|
import eu.eudat.queryable.jpa.hibernatequeryablelist.QueryableHibernateList;
|
2018-03-21 11:16:32 +01:00
|
|
|
import eu.eudat.queryable.queryableentity.DataEntity;
|
2017-12-17 22:34:24 +01:00
|
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
2018-10-02 16:33:58 +02:00
|
|
|
import org.springframework.context.annotation.Scope;
|
2017-12-17 22:34:24 +01:00
|
|
|
import org.springframework.stereotype.Repository;
|
2018-02-07 10:56:30 +01:00
|
|
|
import org.springframework.transaction.annotation.Transactional;
|
2017-12-17 22:34:24 +01:00
|
|
|
|
2018-02-16 11:34:02 +01:00
|
|
|
import javax.persistence.EntityManager;
|
|
|
|
import javax.persistence.EntityManagerFactory;
|
|
|
|
import javax.persistence.PersistenceContext;
|
2017-12-17 22:34:24 +01:00
|
|
|
|
2018-02-01 10:08:06 +01:00
|
|
|
|
2017-12-17 22:34:24 +01:00
|
|
|
@Repository("databaseCtx")
|
2018-02-20 08:50:17 +01:00
|
|
|
public class DatabaseContext<T extends DataEntity> {
|
2018-02-07 10:56:30 +01:00
|
|
|
|
|
|
|
@PersistenceContext
|
2017-12-17 22:34:24 +01:00
|
|
|
private EntityManager entityManager;
|
|
|
|
|
2018-02-07 10:56:30 +01:00
|
|
|
@Autowired
|
|
|
|
public DatabaseContext(EntityManagerFactory entityManagerFactory) {
|
|
|
|
this.entityManager = entityManagerFactory.createEntityManager();
|
|
|
|
}
|
|
|
|
|
2017-12-17 22:34:24 +01:00
|
|
|
public QueryableList<T> getQueryable(Class<T> type) {
|
|
|
|
return new QueryableHibernateList<>(this.entityManager, type).setEntity(type);
|
|
|
|
}
|
|
|
|
|
2018-02-07 10:56:30 +01:00
|
|
|
@Transactional
|
2017-12-17 22:34:24 +01:00
|
|
|
public T createOrUpdate(T item, Class<T> type) {
|
2018-02-07 10:56:30 +01:00
|
|
|
EntityManager entityManager = this.entityManager;
|
2018-02-20 08:50:17 +01:00
|
|
|
if (item.getKeys() != null) {
|
|
|
|
T oldItem = entityManager.find(type, item.getKeys());
|
2018-02-16 11:34:02 +01:00
|
|
|
if (oldItem != null) {
|
2017-12-19 17:22:30 +01:00
|
|
|
oldItem.update(item);
|
|
|
|
entityManager.merge(oldItem);
|
|
|
|
return oldItem;
|
2018-02-16 11:34:02 +01:00
|
|
|
} else {
|
2017-12-19 17:22:30 +01:00
|
|
|
entityManager.persist(item);
|
|
|
|
}
|
2017-12-17 22:34:24 +01:00
|
|
|
} else entityManager.persist(item);
|
|
|
|
return item;
|
|
|
|
}
|
|
|
|
|
2018-02-16 11:34:02 +01:00
|
|
|
public void delete(T item) {
|
2018-01-25 16:24:21 +01:00
|
|
|
this.entityManager.remove(item);
|
|
|
|
}
|
2017-12-17 22:34:24 +01:00
|
|
|
}
|