All Downloads are FREE. Search and download functionalities are using the official Maven repository.

fatjar.implementations.emdb.EntityDB Maven / Gradle / Ivy

There is a newer version: 1.3.0
Show newest version
package fatjar.implementations.emdb;


import fatjar.DB;
import fatjar.Log;

import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class EntityDB implements DB {

    private static EntityManagerFactory entityManagerFactory;
    private EntityManager entityManager;

    private String getJdbcURL() {
        String jdbcURL = null;
        try {
            if (System.getenv("DATABASE_URL") != null) {
                URI dbUri = null;
                dbUri = new URI(System.getenv("DATABASE_URL"));
                String username = dbUri.getUserInfo().split(":")[0];
                String password = dbUri.getUserInfo().split(":")[1];
                jdbcURL = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath();
                Log.info("using jdbcURL: " + jdbcURL);
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return jdbcURL;
    }

    public EntityDB() {
        String jdbcURL = getJdbcURL();
        if (jdbcURL != null) {
            Map map = new HashMap<>();
            map.put("javax.persistence.jdbc.url", jdbcURL);
            entityManagerFactory = Persistence.createEntityManagerFactory("DefaultPersistenceUnit", map);
        } else {
            entityManagerFactory = Persistence.createEntityManagerFactory("DefaultPersistenceUnit");
        }
    }

    public EntityManagerFactory getEntityManagerFactory() {
        return entityManagerFactory;
    }

    private EntityManager getEntityManager() {
        if (entityManager == null) {
            entityManager = getEntityManagerFactory().createEntityManager();
        }
        return entityManager;
    }

    @Override
    public  long count(Class tClass) {
        CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
        CriteriaQuery criteriaQuery = builder.createQuery(Long.class);
        Root root = criteriaQuery.from(tClass);
        criteriaQuery.select(builder.count(root));
        Long count = Long.valueOf(getEntityManager().createQuery(criteriaQuery).getSingleResult().toString());
        return count;
    }


    @Override
    public  long count(Class tClass, Query query) {
        CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
        CriteriaQuery criteriaQuery = builder.createQuery(Long.class);
        Root root = criteriaQuery.from(tClass);
        criteriaQuery.where(queryToPredicate(builder, root, query));
        criteriaQuery.select(builder.count(root));
        Long count = Long.valueOf(getEntityManager().createQuery(criteriaQuery).getSingleResult().toString());
        return count;
    }

    @Override
    public  Optional insert(T t) {
        T inserted = null;
        try {
            beginTransaction();
            try{
                getEntityManager().persist(t);
                inserted = t;
            }catch (EntityExistsException e){
                inserted = getEntityManager().merge(t);
            }
            commitTransaction();
        } catch (Exception e) {
            rollbackTransaction();
            if (e instanceof IllegalArgumentException) {
                inserted = update(t);
            }
        }
        return Optional.ofNullable(inserted);
    }

    @Override
    public  T update(T t) {
        T updated = null;
        try {
            beginTransaction();
            updated = getEntityManager().merge(t);
            commitTransaction();
        } catch (Exception e) {
            rollbackTransaction();
        }
        return updated;
    }

    @Override
    public  void delete(T t) {
        try {
            beginTransaction();
            if (!getEntityManager().contains(t)) {
                getEntityManager().remove(getEntityManager().merge(t));
            } else {
                getEntityManager().remove(t);
            }
            commitTransaction();
        } catch (Exception e) {
            rollbackTransaction();
        }
    }

    @Override
    public  List findAll(Class typeClass) {
        CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
        CriteriaQuery criteriaQuery = builder.createQuery(typeClass);
        Root root = criteriaQuery.from(typeClass);
        criteriaQuery.select(root);
        List list = getEntityManager().createQuery(criteriaQuery).getResultList();
        return list;
    }

    @Override
    public  T find(Class typeClass, Object primary) {
        return getEntityManager().find(typeClass, primary);
    }

    @Override
    public  List find(Class typeClass, Query query) {
        CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
        CriteriaQuery criteriaQuery = builder.createQuery(typeClass);
        Root root = criteriaQuery.from(typeClass);
        criteriaQuery.where(queryToPredicate(builder, root, query));
        criteriaQuery.select(root);
        List list = getEntityManager().createQuery(criteriaQuery).getResultList();
        return list;
    }

    private Predicate queryToPredicate(CriteriaBuilder builder, Root root, Query query) {
        Predicate result = null;
        if (query.getLeftQuery() != null && query.getRightQuery() != null) {
            Predicate left = queryToPredicate(builder, root, query.getLeftQuery());
            Predicate right = queryToPredicate(builder, root, query.getRightQuery());
            Predicate[] predicates = new Predicate[]{left, right};
            if (AndOr.AND.equals(query.getAndOr())) {
                result = builder.and(predicates);
            } else {
                result = builder.or(predicates);
            }
        } else {
            switch (query.getSign()) {
                case EQ:
                    result = builder.equal(root.get(query.getField()), query.getValue());
                    break;
                case LT:
                    result = builder.lessThan(root.get(query.getField()), Double.valueOf(query.getValue().toString()));
                    break;
                case LTE:
                    result = builder.lessThanOrEqualTo(root.get(query.getField()), Double.valueOf(query.getValue().toString()));
                    break;
                case GT:
                    result = builder.greaterThan(root.get(query.getField()), Double.valueOf(query.getValue().toString()));
                    break;
                case GTE:
                    result = builder.greaterThanOrEqualTo(root.get(query.getField()), Double.valueOf(query.getValue().toString()));
                    break;
                case NEQ:
                    result = builder.notEqual(root.get(query.getField()), Double.valueOf(query.getValue().toString()));
                    break;
            }
        }
        return result;
    }

    private void beginTransaction() {
        if (!getEntityManager().getTransaction().isActive()) {
            getEntityManager().getTransaction().begin();
        }
    }

    private void commitTransaction() {
        if (getEntityManager().getTransaction().isActive()) {
            getEntityManager().getTransaction().commit();
        }
    }

    private void rollbackTransaction() {
        if (getEntityManager().getTransaction().isActive()) {
            getEntityManager().getTransaction().rollback();
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy