Persistence

Changing Persistence Unit dynamically

Keep the persistence unit file (Persistence.xml) as it’s. You can override the properties in it as follows.

EntityManagerFactory managerFactory = null;
Map<String, String> persistenceMap = new HashMap<String, String>();

persistenceMap.put("javax.persistence.jdbc.url", "<url>");
persistenceMap.put("javax.persistence.jdbc.user", "<username>");
persistenceMap.put("javax.persistence.jdbc.password", "<password>");
persistenceMap.put("javax.persistence.jdbc.driver", "<driver>");

managerFactory = Persistence.createEntityManagerFactory("<current persistence unit>", persistenceMap);
manager = managerFactory.createEntityManager();

Bulk update with JPA CriteriaUpdate

public void bulkUpdatePricesInLocal() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaUpdate<ProductEntity> cu = cb.createCriteriaUpdate(ProductEntity.class);
    Root<ProductEntity> root = cu.from(ProductEntity.class);
    Join<ProductEntity, CurrencyEntity> currencyToConsumer = root.join(ProductEntity_.currencyToConsumer);
    Join<ProductEntity, CurrencyEntity> currencyToRetailer = root.join(ProductEntity_.currencyToRetailer);

    Expression<BigDecimal> prodConsumer = cb.prod(root.<BigDecimal>get(ProductEntity_.priceToConsumer), currencyToConsumer.<BigDecimal>get(CurrencyEntity_.rateTCMB));
    Expression<BigDecimal> prodRetailer = cb.prod(root.<BigDecimal>get(ProductEntity_.priceToRetailer), currencyToRetailer.<BigDecimal>get(CurrencyEntity_.rateTCMB));

    cu.set(root.get(ProductEntity_.priceToConsumerInLocal), prodConsumer);
    cu.set(root.get(ProductEntity_.priceToRetailerInLocal), prodRetailer);

    Query query = em.createQuery(cu);
    int resultList = query.executeUpdate();
}