Skip to content

Commit

Permalink
BAEL-2814 Added files for article (eugenp#6968)
Browse files Browse the repository at this point in the history
  • Loading branch information
priyeshmashelkar authored and jzheaux committed May 22, 2019
1 parent cb810de commit 93f54b1
Show file tree
Hide file tree
Showing 7 changed files with 408 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package com.baeldung.jpa.projections;

import java.math.BigDecimal;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Product {
@Id
private long id;
private String name;
private String description;
private String category;
private BigDecimal unitPrice;

public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public BigDecimal getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(BigDecimal unitPrice) {
this.unitPrice = unitPrice;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package com.baeldung.jpa.projections;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.Tuple;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

public class ProductRepository {
private EntityManager entityManager;

public ProductRepository() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa-projections");
entityManager = factory.createEntityManager();
}

@SuppressWarnings("unchecked")
public List<Object> findAllNamesUsingJPQL() {
Query query = entityManager.createQuery("select name from Product");
List<Object> resultList = query.getResultList();
return resultList;
}

@SuppressWarnings("unchecked")
public List<Object> findAllIdsUsingJPQL() {
Query query = entityManager.createQuery("select id from Product");
List<Object> resultList = query.getResultList();
return resultList;
}

public List<String> findAllNamesUsingCriteriaBuilder() {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<String> query = builder.createQuery(String.class);
Root<Product> product = query.from(Product.class);
query.select(product.get("name"));
List<String> resultList = entityManager.createQuery(query).getResultList();
return resultList;
}

@SuppressWarnings("unchecked")
public List<Object[]> findAllIdAndNamesUsingJPQL() {
Query query = entityManager.createQuery("select id, name from Product");
List<Object[]> resultList = query.getResultList();
return resultList;
}

public List<Object[]> findAllIdAndNamesUsingCriteriaBuilderArray() {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object[]> query = builder.createQuery(Object[].class);
Root<Product> product = query.from(Product.class);
query.select(builder.array(product.get("id"), product.get("name")));
List<Object[]> resultList = entityManager.createQuery(query).getResultList();
return resultList;
}

public List<Object[]> findAllIdNameUnitPriceUsingCriteriaQueryMultiselect() {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object[]> query = builder.createQuery(Object[].class);
Root<Product> product = query.from(Product.class);
query.multiselect(product.get("id"), product.get("name"), product.get("unitPrice"));
List<Object[]> resultList = entityManager.createQuery(query).getResultList();
return resultList;
}

public List<Tuple> findAllIdAndNamesUsingCriteriaBuilderTuple() {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Tuple> query = builder.createQuery(Tuple.class);
Root<Product> product = query.from(Product.class);
query.select(builder.tuple(product.get("id"), product.get("name")));
List<Tuple> resultList = entityManager.createQuery(query).getResultList();
return resultList;
}

public List<Object[]> findCountByCategoryUsingJPQL() {
Query query = entityManager.createQuery("select p.category, count(p) from Product p group by p.category");
return query.getResultList();
}

public List<Object[]> findCountByCategoryUsingCriteriaBuilder() {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object[]> query = builder.createQuery(Object[].class);
Root<Product> product = query.from(Product.class);
query.multiselect(product.get("category"), builder.count(product));
query.groupBy(product.get("category"));
List<Object[]> resultList = entityManager.createQuery(query).getResultList();
return resultList;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false" />
</properties>
</persistence-unit>

<persistence-unit name="jpa-entity-definition">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.entity.Student</class>
Expand All @@ -163,4 +163,21 @@
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false" />
</properties>
</persistence-unit>

<persistence-unit name="jpa-projections">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.projections.Product</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="show_sql" value="true"/>
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
<property name="javax.persistence.sql-load-script-source" value="products_jpa.sql"/>
</properties>
</persistence-unit>
</persistence>
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
insert into product(id, name, description, category) values (1,'Product Name 1','This is Product 1', 'category1');
insert into product(id, name, description, category) values (2,'Product Name 2','This is Product 2', 'category1');
insert into product(id, name, description, category) values (3,'Product Name 3','This is Product 3', 'category2');
insert into product(id, name, description, category) values (4,'Product Name 4','This is Product 4', 'category3');
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package com.baeldung.jpa.projections;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class HibernateProjectionsIntegrationTest {
private static Session session;
private static SessionFactory sessionFactory;
private Transaction transaction;

@BeforeClass
public static void init() {
Configuration configuration = getConfiguration();
configuration.addAnnotatedClass(Product.class);
sessionFactory = configuration.buildSessionFactory();
}

@Before
public void before() {
session = sessionFactory.getCurrentSession();
transaction = session.beginTransaction();
}

@After
public void after() {
if(transaction.isActive()) {
transaction.rollback();
}
}

private static Configuration getConfiguration() {
Configuration cfg = new Configuration();
cfg.setProperty(AvailableSettings.DIALECT,
"org.hibernate.dialect.H2Dialect");
cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "none");
cfg.setProperty(AvailableSettings.DRIVER, "org.h2.Driver");
cfg.setProperty(AvailableSettings.URL,
"jdbc:h2:mem:myexceptiondb2;DB_CLOSE_DELAY=-1;;INIT=RUNSCRIPT FROM 'src/test/resources/products.sql'");
cfg.setProperty(AvailableSettings.USER, "sa");
cfg.setProperty(AvailableSettings.PASS, "");
cfg.setProperty(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, "thread");
return cfg;
}


@SuppressWarnings("deprecation")
@Test
public void givenProductData_whenIdAndNameProjectionUsingCriteria_thenListOfObjectArrayReturned() {
Criteria criteria = session.createCriteria(Product.class);
criteria = criteria.setProjection(Projections.projectionList()
.add(Projections.id())
.add(Projections.property("name")));
List<Object[]> resultList = criteria.list();

assertNotNull(resultList);
assertEquals(4, resultList.size());
assertEquals(1L, resultList.get(0)[0]);
assertEquals("Product Name 1", resultList.get(0)[1]);
assertEquals(2L, resultList.get(1)[0]);
assertEquals("Product Name 2", resultList.get(1)[1]);
assertEquals(3L, resultList.get(2)[0]);
assertEquals("Product Name 3", resultList.get(2)[1]);
assertEquals(4L, resultList.get(3)[0]);
assertEquals("Product Name 4", resultList.get(3)[1]);
}


@Test
public void givenProductData_whenNameProjectionUsingCriteria_thenListOfStringReturned() {
Criteria criteria = session.createCriteria(Product.class);
criteria = criteria.setProjection(Projections.property("name"));
List resultList = criteria.list();

assertNotNull(resultList);
assertEquals(4, resultList.size());
assertEquals("Product Name 1", resultList.get(0));
assertEquals("Product Name 2", resultList.get(1));
assertEquals("Product Name 3", resultList.get(2));
assertEquals("Product Name 4", resultList.get(3));
}

@Test
public void givenProductData_whenCountByCategoryUsingCriteria_thenOK() {
Criteria criteria = session.createCriteria(Product.class);
criteria = criteria.setProjection(Projections.projectionList()
.add(Projections.groupProperty("category"))
.add(Projections.rowCount()));
List<Object[]> resultList = criteria.list();

assertNotNull(resultList);
assertEquals(3, resultList.size());
assertEquals("category1", resultList.get(0)[0]);
assertEquals(2L, resultList.get(0)[1]);
assertEquals("category2", resultList.get(1)[0]);
assertEquals(1L, resultList.get(1)[1]);
assertEquals("category3", resultList.get(2)[0]);
assertEquals(1L, resultList.get(2)[1]);
}

@Test
public void givenProductData_whenCountByCategoryWithAliasUsingCriteria_thenOK() {
Criteria criteria = session.createCriteria(Product.class);
criteria = criteria.setProjection(Projections.projectionList()
.add(Projections.groupProperty("category"))
.add(Projections.alias(Projections.rowCount(), "count")));
criteria.addOrder(Order.asc("count"));
List<Object[]> resultList = criteria.list();

assertNotNull(resultList);
assertEquals(3, resultList.size());
assertEquals("category2", resultList.get(0)[0]);
assertEquals(1L, resultList.get(0)[1]);
assertEquals("category3", resultList.get(1)[0]);
assertEquals(1L, resultList.get(1)[1]);
assertEquals("category1", resultList.get(2)[0]);
assertEquals(2L, resultList.get(2)[1]);
}
}
Loading

0 comments on commit 93f54b1

Please sign in to comment.