Merge branch 'master' into master

This commit is contained in:
Loredana Crusoveanu
2019-06-08 14:11:25 +03:00
committed by GitHub
508 changed files with 16341 additions and 2717 deletions

View File

@@ -2,7 +2,7 @@
- [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping)
- [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures)
- [Fixing the JPA error “java.lang.String cannot be cast to [Ljava.lang.String;”]](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast)
- [Fixing the JPA error “java.lang.String cannot be cast to Ljava.lang.String;”](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast)
- [JPA Entity Graph](https://www.baeldung.com/jpa-entity-graph)
- [JPA 2.2 Support for Java 8 Date/Time Types](https://www.baeldung.com/jpa-java-time)
- [Converting Between LocalDate and SQL Date](https://www.baeldung.com/java-convert-localdate-sql-date)
@@ -10,3 +10,6 @@
- [Types of JPA Queries](https://www.baeldung.com/jpa-queries)
- [JPA/Hibernate Projections](https://www.baeldung.com/jpa-hibernate-projections)
- [Composite Primary Keys in JPA](https://www.baeldung.com/jpa-composite-primary-keys)
- [Defining JPA Entities](https://www.baeldung.com/jpa-entities)
- [JPA @Basic Annotation](https://www.baeldung.com/jpa-basic-annotation)
- [Default Column Values in JPA](https://www.baeldung.com/jpa-default-column-values)

View File

@@ -0,0 +1,43 @@
package com.baeldung.jpa.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
@Entity
@IdClass(AccountId.class)
public class Account {
@Id
private String accountNumber;
@Id
private String accountType;
private String description;
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@@ -0,0 +1,52 @@
package com.baeldung.jpa.entity;
import java.io.Serializable;
public class AccountId implements Serializable {
private static final long serialVersionUID = 1L;
private String accountNumber;
private String accountType;
public AccountId() {
}
public AccountId(String accountNumber, String accountType) {
this.accountNumber = accountNumber;
this.accountType = accountType;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((accountNumber == null) ? 0 : accountNumber.hashCode());
result = prime * result + ((accountType == null) ? 0 : accountType.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AccountId other = (AccountId) obj;
if (accountNumber == null) {
if (other.accountNumber != null)
return false;
} else if (!accountNumber.equals(other.accountNumber))
return false;
if (accountType == null) {
if (other.accountType != null)
return false;
} else if (!accountType.equals(other.accountType))
return false;
return true;
}
}

View File

@@ -0,0 +1,34 @@
package com.baeldung.jpa.entity;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
@Entity
public class Book {
@EmbeddedId
private BookId bookId;
private String description;
public Book() {
}
public Book(BookId bookId) {
this.bookId = bookId;
}
public BookId getBookId() {
return bookId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@@ -0,0 +1,62 @@
package com.baeldung.jpa.entity;
import java.io.Serializable;
import javax.persistence.Embeddable;
@Embeddable
public class BookId implements Serializable {
private static final long serialVersionUID = 1L;
private String title;
private String language;
public BookId() {
}
public BookId(String title, String language) {
this.title = title;
this.language = language;
}
public String getTitle() {
return title;
}
public String getLanguage() {
return language;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((language == null) ? 0 : language.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BookId other = (BookId) obj;
if (language == null) {
if (other.language != null)
return false;
} else if (!language.equals(other.language))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
}

View File

@@ -0,0 +1,75 @@
package com.baeldung.jpa.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import com.baeldung.util.Gender;
@Entity
@Table(name="STUDENT")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "STUDENT_NAME", length = 50, nullable = false, unique = false)
private String name;
@Transient
private Integer age;
@Temporal(TemporalType.DATE)
private Date birthDate;
@Enumerated(EnumType.STRING)
private Gender gender;
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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
}

View File

@@ -0,0 +1,91 @@
package com.baeldung.jpa.enums;
import javax.persistence.*;
@Entity
public class Article {
@Id
private int id;
private String title;
@Enumerated(EnumType.ORDINAL)
private Status status;
@Enumerated(EnumType.STRING)
private Type type;
@Basic
private int priorityValue;
@Transient
private Priority priority;
private Category category;
public Article() {
}
@PostLoad
void fillTransient() {
if (priorityValue > 0) {
this.priority = Priority.of(priorityValue);
}
}
@PrePersist
void fillPersistent() {
if (priority != null) {
this.priorityValue = priority.getPriority();
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public Priority getPriority() {
return priority;
}
public void setPriority(Priority priority) {
this.priority = priority;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.jpa.enums;
import java.util.stream.Stream;
public enum Category {
SPORT("S"), MUSIC("M"), TECHNOLOGY("T");
private String code;
Category(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}

View File

@@ -0,0 +1,28 @@
package com.baeldung.jpa.enums;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.stream.Stream;
@Converter(autoApply = true)
public class CategoryConverter implements AttributeConverter<Category, String> {
@Override
public String convertToDatabaseColumn(Category category) {
if (category == null) {
return null;
}
return category.getCode();
}
@Override
public Category convertToEntityAttribute(final String code) {
if (code == null) {
return null;
}
return Stream.of(Category.values())
.filter(c -> c.getCode().equals(code))
.findFirst()
.orElseThrow(IllegalArgumentException::new);
}
}

View File

@@ -0,0 +1,24 @@
package com.baeldung.jpa.enums;
import java.util.stream.Stream;
public enum Priority {
LOW(100), MEDIUM(200), HIGH(300);
private int priority;
private Priority(int priority) {
this.priority = priority;
}
public int getPriority() {
return priority;
}
public static Priority of(int priority) {
return Stream.of(Priority.values())
.filter(p -> p.getPriority() == priority)
.findFirst()
.orElseThrow(IllegalArgumentException::new);
}
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.jpa.enums;
public enum Status {
OPEN, REVIEW, APPROVED, REJECTED;
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.jpa.enums;
enum Type {
INTERNAL, EXTERNAL;
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -0,0 +1,6 @@
package com.baeldung.util;
public enum Gender {
MALE,
FEMALE
}

View File

@@ -1,149 +1,227 @@
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
version="2.2">
version="2.2">
<persistence-unit name="java-jpa-scheduled-day">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.sqlresultsetmapping.ScheduledDay</class>
<class>com.baeldung.sqlresultsetmapping.Employee</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;INIT=RUNSCRIPT FROM 'classpath:database.sql'"/>
<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"/>
</properties>
</persistence-unit>
<persistence-unit name="java-jpa-scheduled-day">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.sqlresultsetmapping.ScheduledDay</class>
<class>com.baeldung.sqlresultsetmapping.Employee</class>
<class>com.baeldung.jpa.basicannotation.Course</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;INIT=RUNSCRIPT FROM 'classpath:database.sql'" />
<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" />
</properties>
</persistence-unit>
<persistence-unit name="jpa-h2">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.stringcast.Message</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"/>
</properties>
</persistence-unit>
<persistence-unit name="jpa-h2">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.stringcast.Message</class>
<class>com.baeldung.jpa.enums.Article</class>
<class>com.baeldung.jpa.enums.CategoryConverter</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" />
</properties>
</persistence-unit>
<persistence-unit name="jpa-db">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.model.Car</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/baeldung"/>
<property name="javax.persistence.jdbc.user" value="baeldung"/>
<property name="javax.persistence.jdbc.password" value="YourPassword"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
<persistence-unit name="jpa-db">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.model.Car</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver"
value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://127.0.0.1:3306/baeldung" />
<property name="javax.persistence.jdbc.user"
value="baeldung" />
<property name="javax.persistence.jdbc.password"
value="YourPassword" />
<property name="hibernate.dialect"
value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
<persistence-unit name="entity-graph-pu" transaction-type="RESOURCE_LOCAL">
<class>com.baeldung.jpa.entitygraph.model.Post</class>
<class>com.baeldung.jpa.entitygraph.model.User</class>
<class>com.baeldung.jpa.entitygraph.model.Comment</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<persistence-unit name="entity-graph-pu"
transaction-type="RESOURCE_LOCAL">
<class>com.baeldung.jpa.entitygraph.model.Post</class>
<class>com.baeldung.jpa.entitygraph.model.User</class>
<class>com.baeldung.jpa.entitygraph.model.Comment</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<!--H2-->
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:h2:mem:entitygraphdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"/>
<!--H2 -->
<property name="javax.persistence.jdbc.driver"
value="org.h2.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:h2:mem:entitygraphdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE" />
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="javax.persistence.sql-load-script-source" value="data-init.sql"/>
</properties>
</persistence-unit>
<property
name="javax.persistence.schema-generation.database.action"
value="drop-and-create" />
<property name="javax.persistence.sql-load-script-source"
value="data-init.sql" />
</properties>
</persistence-unit>
<persistence-unit name="java8-datetime-postgresql" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.baeldung.jpa.datetime.JPA22DateTimeEntity</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/java8-datetime2"/>
<property name="javax.persistence.jdbc.user" value="postgres"/>
<property name="javax.persistence.jdbc.password" value="postgres"/>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<persistence-unit name="java8-datetime-postgresql"
transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.baeldung.jpa.datetime.JPA22DateTimeEntity</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver"
value="org.postgresql.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:postgresql://localhost:5432/java8-datetime2" />
<property name="javax.persistence.jdbc.user"
value="postgres" />
<property name="javax.persistence.jdbc.password"
value="postgres" />
<property
name="javax.persistence.schema-generation.database.action"
value="drop-and-create" />
<!-- configure logging -->
<property name="eclipselink.logging.level" value="INFO"/>
<property name="eclipselink.logging.level.sql" value="FINE"/>
<property name="eclipselink.logging.parameters" value="true"/>
</properties>
</persistence-unit>
<!-- configure logging -->
<property name="eclipselink.logging.level" value="INFO" />
<property name="eclipselink.logging.level.sql" value="FINE" />
<property name="eclipselink.logging.parameters" value="true" />
</properties>
</persistence-unit>
<persistence-unit name="jpa-h2-criteria">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.criteria.entity.Item</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="item.sql"/>
</properties>
</persistence-unit>
<persistence-unit name="jpa-h2-criteria">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.criteria.entity.Item</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="item.sql" />
</properties>
</persistence-unit>
<persistence-unit name="jpa-query-types">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.querytypes.UserEntity</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="users.sql"/>
</properties>
</persistence-unit>
<persistence-unit name="jpa-query-types">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.querytypes.UserEntity</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="users.sql" />
</properties>
</persistence-unit>
<persistence-unit name="entity-default-values">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.defaultvalues.User</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" />
</properties>
</persistence-unit>
<persistence-unit name="entity-default-values">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.defaultvalues.User</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" />
</properties>
</persistence-unit>
</persistence>
<persistence-unit name="jpa-entity-definition">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.entity.Student</class>
<class>com.baeldung.jpa.entity.Book</class>
<class>com.baeldung.jpa.entity.BookId</class>
<class>com.baeldung.jpa.entity.Account</class>
<class>com.baeldung.jpa.entity.AccountId</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" />
</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>

View File

@@ -15,3 +15,7 @@ INSERT INTO SCHEDULE_DAYS (employeeId, dayOfWeek) VALUES (1, 'FRIDAY');
INSERT INTO SCHEDULE_DAYS (employeeId, dayOfWeek) VALUES (2, 'SATURDAY');
INSERT INTO SCHEDULE_DAYS (employeeId, dayOfWeek) VALUES (3, 'MONDAY');
INSERT INTO SCHEDULE_DAYS (employeeId, dayOfWeek) VALUES (3, 'FRIDAY');
CREATE TABLE COURSE
(id BIGINT,
name VARCHAR(10));

View File

@@ -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');

View File

@@ -1,16 +1,13 @@
package com.baeldung.jpa.basicannotation;
import org.hibernate.PropertyValueException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import javax.persistence.PersistenceException;
import java.io.IOException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class BasicAnnotationIntegrationTest {
@@ -18,9 +15,10 @@ public class BasicAnnotationIntegrationTest {
private static EntityManagerFactory entityManagerFactory;
@BeforeClass
public void setup() {
public static void setup() {
entityManagerFactory = Persistence.createEntityManagerFactory("java-jpa-scheduled-day");
entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
}
@Test
@@ -34,7 +32,7 @@ public class BasicAnnotationIntegrationTest {
}
@Test(expected = PropertyValueException.class)
@Test(expected = PersistenceException.class)
public void givenACourse_whenCourseNameAbsent_shouldFail() {
Course course = new Course();
@@ -44,7 +42,7 @@ public class BasicAnnotationIntegrationTest {
}
@AfterClass
public void destroy() {
public static void destroy() {
if (entityManager != null) {
entityManager.close();

View File

@@ -0,0 +1,114 @@
package com.baeldung.jpa.entity;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class CompositeKeysIntegrationTest {
private static final String SAVINGS_ACCOUNT = "Savings";
private static final String ACCOUNT_NUMBER = "JXSDF324234";
private static final String ENGLISH = "English";
private static final String WAR_AND_PEACE = "War and Peace";
private static EntityManagerFactory emf;
private static EntityManager em;
@BeforeClass
public static void setup() {
emf = Persistence.createEntityManagerFactory("jpa-entity-definition");
em = emf.createEntityManager();
}
@Test
public void persistBookWithCompositeKeyThenRetrieveDetails() {
Book warAndPeace = createBook();
persist(warAndPeace);
clearThePersistenceContext();
Book book = findBookByBookId();
verifyAssertionsWith(book);
}
@Test
public void persistAccountWithCompositeKeyThenRetrieveDetails() {
Account savingsAccount = createAccount();
persist(savingsAccount);
clearThePersistenceContext();
Account account = findAccountByAccountId();
verifyAssertionsWith(account);
}
@AfterClass
public static void destroy() {
if (em != null) {
em.close();
}
if (emf != null) {
emf.close();
}
}
private Account createAccount() {
Account savingsAccount = new Account();
savingsAccount.setAccountNumber(ACCOUNT_NUMBER);
savingsAccount.setAccountType(SAVINGS_ACCOUNT);
savingsAccount.setDescription("Savings account");
return savingsAccount;
}
private void verifyAssertionsWith(Account account) {
assertEquals(ACCOUNT_NUMBER, account.getAccountNumber());
assertEquals(SAVINGS_ACCOUNT, account.getAccountType());
}
private Account findAccountByAccountId() {
return em.find(Account.class, new AccountId(ACCOUNT_NUMBER, SAVINGS_ACCOUNT));
}
private void persist(Account account) {
em.getTransaction()
.begin();
em.persist(account);
em.getTransaction()
.commit();
}
private Book findBookByBookId() {
return em.find(Book.class, new BookId(WAR_AND_PEACE, ENGLISH));
}
private Book createBook() {
BookId bookId = new BookId(WAR_AND_PEACE, ENGLISH);
Book warAndPeace = new Book(bookId);
warAndPeace.setDescription("Novel and Historical Fiction");
return warAndPeace;
}
private void verifyAssertionsWith(Book book) {
assertNotNull(book);
assertNotNull(book.getBookId());
assertEquals(WAR_AND_PEACE, book.getBookId()
.getTitle());
assertEquals(ENGLISH, book.getBookId()
.getLanguage());
}
private void persist(Book book) {
em.getTransaction()
.begin();
em.persist(book);
em.getTransaction()
.commit();
}
private void clearThePersistenceContext() {
em.clear();
}
}

View File

@@ -0,0 +1,91 @@
package com.baeldung.jpa.entity;
import static org.junit.Assert.assertEquals;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.util.Gender;
public class StudentEntityIntegrationTest {
private EntityManagerFactory emf;
private EntityManager em;
@Before
public void setup() {
emf = Persistence.createEntityManagerFactory("jpa-entity-definition");
em = emf.createEntityManager();
}
@Test
public void persistStudentThenRetrieveTheDetails() {
Student student = createStudentWithRelevantDetails();
persist(student);
clearThePersistenceContext();
List<Student> students = getStudentsFromTable();
checkAssertionsWith(students);
}
@After
public void destroy() {
if (em != null) {
em.close();
}
if (emf != null) {
emf.close();
}
}
private void clearThePersistenceContext() {
em.clear();
}
private void checkAssertionsWith(List<Student> students) {
assertEquals(1, students.size());
Student john = students.get(0);
assertEquals(1L, john.getId().longValue());
assertEquals(null, john.getAge());
assertEquals("John", john.getName());
}
private List<Student> getStudentsFromTable() {
String selectQuery = "SELECT student FROM Student student";
TypedQuery<Student> selectFromStudentTypedQuery = em.createQuery(selectQuery, Student.class);
List<Student> students = selectFromStudentTypedQuery.getResultList();
return students;
}
private void persist(Student student) {
em.getTransaction().begin();
em.persist(student);
em.getTransaction().commit();
}
private Student createStudentWithRelevantDetails() {
Student student = new Student();
student.setAge(20); // the 'age' field has been annotated with @Transient
student.setName("John");
Date date = getDate();
student.setBirthDate(date);
student.setGender(Gender.MALE);
return student;
}
private Date getDate() {
LocalDate localDate = LocalDate.of(2008, 7, 20);
return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
}
}

View File

@@ -0,0 +1,118 @@
package com.baeldung.jpa.enums;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ArticleUnitTest {
private static EntityManager em;
private static EntityManagerFactory emFactory;
@BeforeClass
public static void setup() {
Map properties = new HashMap();
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
emFactory = Persistence.createEntityManagerFactory("jpa-h2", properties);
em = emFactory.createEntityManager();
}
@Test
public void shouldPersistStatusEnumOrdinalValue() {
// given
Article article = new Article();
article.setId(1);
article.setTitle("ordinal title");
article.setStatus(Status.OPEN);
// when
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(article);
tx.commit();
// then
Article persistedArticle = em.find(Article.class, 1);
assertEquals(1, persistedArticle.getId());
assertEquals("ordinal title", persistedArticle.getTitle());
assertEquals(Status.OPEN, persistedArticle.getStatus());
}
@Test
public void shouldPersistTypeEnumStringValue() {
// given
Article article = new Article();
article.setId(2);
article.setTitle("string title");
article.setType(Type.EXTERNAL);
// when
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(article);
tx.commit();
// then
Article persistedArticle = em.find(Article.class, 2);
assertEquals(2, persistedArticle.getId());
assertEquals("string title", persistedArticle.getTitle());
assertEquals(Type.EXTERNAL, persistedArticle.getType());
}
@Test
public void shouldPersistPriorityIntValue() {
// given
Article article = new Article();
article.setId(3);
article.setTitle("callback title");
article.setPriority(Priority.HIGH);
// when
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(article);
tx.commit();
// then
Article persistedArticle = em.find(Article.class, 3);
assertEquals(3, persistedArticle.getId());
assertEquals("callback title", persistedArticle.getTitle());
assertEquals(Priority.HIGH, persistedArticle.getPriority());
}
@Test
public void shouldPersistCategoryEnumConvertedValue() {
// given
Article article = new Article();
article.setId(4);
article.setTitle("converted title");
article.setCategory(Category.MUSIC);
// when
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(article);
tx.commit();
// then
Article persistedArticle = em.find(Article.class, 4);
assertEquals(4, persistedArticle.getId());
assertEquals("converted title", persistedArticle.getTitle());
assertEquals(Category.MUSIC, persistedArticle.getCategory());
}
}

View File

@@ -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]);
}
}

View File

@@ -0,0 +1,105 @@
package com.baeldung.jpa.projections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
public class ProductRepositoryIntegrationTest {
private static ProductRepository productRepository;
@BeforeClass
public static void once() throws IOException {
productRepository = new ProductRepository();
}
@Test
public void givenProductData_whenIdAndNameProjectionUsingJPQL_thenListOfObjectArrayReturned() {
List<Object[]> resultList = productRepository.findAllIdAndNamesUsingJPQL();
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_whenIdAndNameProjectionUsingCriteriaBuilder_thenListOfObjectArrayReturned() {
List<Object[]> resultList = productRepository.findAllIdAndNamesUsingCriteriaBuilderArray();
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]);
}
@SuppressWarnings("rawtypes")
@Test
public void givenProductData_whenNameProjectionUsingJPQL_thenListOfStringReturned() {
List resultList = productRepository.findAllNamesUsingJPQL();
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_whenNameProjectionUsingCriteriaBuilder_thenListOfStringReturned() {
List<String> resultList = productRepository.findAllNamesUsingCriteriaBuilder();
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_whenCountByCategoryUsingJPQL_thenOK() {
List<Object[]> resultList = productRepository.findCountByCategoryUsingJPQL();
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_whenCountByCategoryUsingCriteriaBuider_thenOK() {
List<Object[]> resultList = productRepository.findCountByCategoryUsingCriteriaBuilder();
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]);
}
}

View File

@@ -0,0 +1,5 @@
create table Product (id bigint not null, category varchar(255), description varchar(255), name varchar(255), unitPrice decimal(19,2), primary key (id));
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');