Merge branch 'master' of https://github.com/eugenp/tutorials into BAEL-2967

This commit is contained in:
Alessio Stalla
2019-06-05 22:18:03 +02:00
205 changed files with 4417 additions and 2070 deletions
-17
View File
@@ -1,17 +0,0 @@
## Persistence Modules
### Relevant Articles:
- [Introduction to Hibernate Search](http://www.baeldung.com/hibernate-search)
- [Introduction to Lettuce the Java Redis Client](http://www.baeldung.com/java-redis-lettuce)
- [A Guide to Jdbi](http://www.baeldung.com/jdbi)
- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking)
- [Get All Data from a Table with Hibernate](https://www.baeldung.com/hibernate-select-all)
- [Spring Data with Reactive Cassandra](https://www.baeldung.com/spring-data-cassandra-reactive)
- [Spring Data JPA Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby)
- [Difference Between save() and saveAndFlush() in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-save-saveandflush)
- [Spring Boot with Hibernate](https://www.baeldung.com/spring-boot-hibernate)
- [Persisting Maps with Hibernate](https://www.baeldung.com/hibernate-persisting-maps)
- [Difference Between @Size, @Length, and @Column(length=value)](https://www.baeldung.com/jpa-size-length-column-differences)
@@ -2,3 +2,4 @@
### Relevant Articles:
- [Persisting Maps with Hibernate](https://www.baeldung.com/hibernate-persisting-maps)
- [Difference Between @Size, @Length, and @Column(length=value)](https://www.baeldung.com/jpa-size-length-column-differences)
@@ -12,16 +12,12 @@ import java.net.URL;
import java.util.Properties;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private HibernateUtil() {
}
public static SessionFactory getSessionFactory(Strategy strategy) {
if (sessionFactory == null) {
sessionFactory = buildSessionFactory(strategy);
}
return sessionFactory;
return buildSessionFactory(strategy);
}
private static SessionFactory buildSessionFactory(Strategy strategy) {
@@ -2,12 +2,12 @@ package com.baeldung.hibernate;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public enum Strategy {
//See that the classes belongs to different packages
MAP_KEY_COLUMN_BASED(Collections.singletonList(com.baeldung.hibernate.persistmaps.mapkeycolumn.Order.class)),
MAP_KEY_COLUMN_BASED(Arrays.asList(com.baeldung.hibernate.persistmaps.mapkeycolumn.Order.class,
com.baeldung.hibernate.basicannotation.Course.class)),
MAP_KEY_BASED(Arrays.asList(com.baeldung.hibernate.persistmaps.mapkey.Item.class,
com.baeldung.hibernate.persistmaps.mapkey.Order.class,com.baeldung.hibernate.persistmaps.mapkey.User.class)),
MAP_KEY_JOIN_COLUMN_BASED(Arrays.asList(com.baeldung.hibernate.persistmaps.mapkeyjoincolumn.Seller.class,
@@ -1,18 +1,19 @@
package com.baeldung.hibernate.basicannotation;
import com.baeldung.hibernate.HibernateUtil;
import com.baeldung.hibernate.basicannotation.Course;
import com.baeldung.hibernate.Strategy;
import org.hibernate.PropertyValueException;
import java.io.IOException;
import javax.persistence.PersistenceException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.hibernate.SessionFactory;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import com.baeldung.hibernate.HibernateUtil;
import com.baeldung.hibernate.Strategy;
public class BasicAnnotationIntegrationTest {
@@ -48,7 +49,7 @@ public class BasicAnnotationIntegrationTest {
}
@Test(expected = PropertyValueException.class)
@Test(expected = PersistenceException.class)
public void givenACourse_whenCourseNameAbsent_shouldFail() {
Course course = new Course();
+14
View File
@@ -37,6 +37,11 @@
<artifactId>hibernate-spatial</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.opengeo</groupId>
<artifactId>geodb</artifactId>
<version>${geodb.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
@@ -99,6 +104,14 @@
</resource>
</resources>
</build>
<repositories>
<repository>
<id>geodb-repo</id>
<name>GeoDB repository</name>
<url>http://repo.boundlessgeo.com/main/</url>
</repository>
</repositories>
<properties>
<hibernate.version>5.3.7.Final</hibernate.version>
@@ -106,6 +119,7 @@
<mariaDB4j.version>2.2.3</mariaDB4j.version>
<assertj-core.version>3.8.0</assertj-core.version>
<openjdk-jmh.version>1.21</openjdk-jmh.version>
<geodb.version>0.9</geodb.version>
</properties>
</project>
@@ -5,27 +5,25 @@ import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import com.baeldung.hibernate.customtypes.LocalDateStringType;
import com.baeldung.hibernate.customtypes.OfficeEmployee;
import com.baeldung.hibernate.entities.DeptEmployee;
import com.baeldung.hibernate.joincolumn.Email;
import com.baeldung.hibernate.joincolumn.Office;
import com.baeldung.hibernate.joincolumn.OfficeAddress;
import com.baeldung.hibernate.optimisticlocking.OptimisticLockingCourse;
import com.baeldung.hibernate.optimisticlocking.OptimisticLockingStudent;
import com.baeldung.hibernate.pessimisticlocking.Individual;
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingCourse;
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingEmployee;
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingStudent;
import com.baeldung.hibernate.pojo.*;
import com.baeldung.hibernate.pojo.Person;
import com.baeldung.hibernate.pojo.inheritance.*;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataBuilder;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import com.baeldung.hibernate.pojo.Course;
import com.baeldung.hibernate.pojo.Employee;
import com.baeldung.hibernate.pojo.EntityDescription;
@@ -36,6 +34,7 @@ import com.baeldung.hibernate.pojo.Person;
import com.baeldung.hibernate.pojo.Phone;
import com.baeldung.hibernate.pojo.PointEntity;
import com.baeldung.hibernate.pojo.PolygonEntity;
import com.baeldung.hibernate.pojo.Post;
import com.baeldung.hibernate.pojo.Product;
import com.baeldung.hibernate.pojo.Student;
import com.baeldung.hibernate.pojo.TemporalValues;
@@ -52,7 +51,6 @@ import com.baeldung.hibernate.pojo.inheritance.Pet;
import com.baeldung.hibernate.pojo.inheritance.Vehicle;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static String PROPERTY_FILE_NAME;
public static SessionFactory getSessionFactory() throws IOException {
@@ -61,11 +59,8 @@ public class HibernateUtil {
public static SessionFactory getSessionFactory(String propertyFileName) throws IOException {
PROPERTY_FILE_NAME = propertyFileName;
if (sessionFactory == null) {
ServiceRegistry serviceRegistry = configureServiceRegistry();
sessionFactory = makeSessionFactory(serviceRegistry);
}
return sessionFactory;
ServiceRegistry serviceRegistry = configureServiceRegistry();
return makeSessionFactory(serviceRegistry);
}
public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException {
@@ -114,6 +109,10 @@ public class HibernateUtil {
metadataSources.addAnnotatedClass(OptimisticLockingStudent.class);
metadataSources.addAnnotatedClass(OfficeEmployee.class);
metadataSources.addAnnotatedClass(Post.class);
metadataSources.addAnnotatedClass(com.baeldung.hibernate.joincolumn.OfficialEmployee.class);
metadataSources.addAnnotatedClass(Email.class);
metadataSources.addAnnotatedClass(Office.class);
metadataSources.addAnnotatedClass(OfficeAddress.class);
Metadata metadata = metadataSources.getMetadataBuilder()
.applyBasicType(LocalDateStringType.INSTANCE)
@@ -19,7 +19,7 @@ public class Email {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "employee_id")
private Employee employee;
private OfficialEmployee employee;
public Long getId() {
return id;
@@ -37,11 +37,11 @@ public class Email {
this.address = address;
}
public Employee getEmployee() {
public OfficialEmployee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
public void setEmployee(OfficialEmployee employee) {
this.employee = employee;
}
}
@@ -21,7 +21,7 @@ public class Office {
@JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
@JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
})
private Address address;
private OfficeAddress address;
public Long getId() {
return id;
@@ -31,11 +31,11 @@ public class Office {
this.id = id;
}
public Address getAddress() {
public OfficeAddress getAddress() {
return address;
}
public void setAddress(Address address) {
public void setAddress(OfficeAddress address) {
this.address = address;
}
}
@@ -7,7 +7,7 @@ import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Address {
public class OfficeAddress {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@@ -9,7 +9,7 @@ import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class Employee {
public class OfficialEmployee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@@ -19,10 +19,7 @@ public class HibernateUtil {
}
public static SessionFactory getSessionFactory(Strategy strategy) {
if (sessionFactory == null) {
sessionFactory = buildSessionFactory(strategy);
}
return sessionFactory;
return buildSessionFactory(strategy);
}
private static SessionFactory buildSessionFactory(Strategy strategy) {
@@ -2,6 +2,7 @@ package com.baeldung.hibernate.pojo;
import com.vividsolutions.jts.geom.Point;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@@ -13,6 +14,7 @@ public class PointEntity {
@GeneratedValue
private Long id;
@Column(columnDefinition="BINARY(2048)")
private Point point;
public PointEntity() {
@@ -122,11 +122,7 @@ public class DynamicMappingIntegrationTest {
Employee employee = session.get(Employee.class, 1);
assertThat(employee.getGrossIncome()).isEqualTo(10_000);
session.close();
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
session.disableFilter("incomeLevelFilter");
employees = session.createQuery("from Employee").getResultList();
assertThat(employees).hasSize(3);
@@ -4,7 +4,10 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import javax.persistence.Query;
@@ -24,6 +27,8 @@ import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
import com.vividsolutions.jts.util.GeometricShapeFactory;
import geodb.GeoDB;
public class HibernateSpatialIntegrationTest {
private Session session;
@@ -34,6 +39,7 @@ public class HibernateSpatialIntegrationTest {
session = HibernateUtil.getSessionFactory("hibernate-spatial.properties")
.openSession();
transaction = session.beginTransaction();
session.doWork(conn -> { GeoDB.InitGeoDB(conn); });
}
@After
@@ -141,4 +147,15 @@ public class HibernateSpatialIntegrationTest {
shapeFactory.setSize(radius * 2);
return shapeFactory.createCircle();
}
public static Properties getProperties(String propertyFile) throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()
.getResource(propertyFile);
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
}
@@ -45,7 +45,7 @@ public class TypeSafeCriteriaIntegrationTest {
CriteriaQuery<Student> criteriaQuery = cb.createQuery(Student.class);
Root<Student> root = criteriaQuery.from(Student.class);
criteriaQuery.select(root).where(cb.equal(root.get(Student_.gradYear), 1965));
criteriaQuery.select(root).where(cb.equal(root.get("gradYear"), 1965));
Query<Student> query = session.createQuery(criteriaQuery);
List<Student> results = query.getResultList();
@@ -32,7 +32,7 @@ public class JoinColumnIntegrationTest {
public void givenOfficeEntity_setAddress_shouldPersist() {
Office office = new Office();
Address address = new Address();
OfficeAddress address = new OfficeAddress();
address.setZipCode("11-111");
office.setAddress(address);
@@ -43,7 +43,7 @@ public class JoinColumnIntegrationTest {
@Test
public void givenEmployeeEntity_setEmails_shouldPersist() {
Employee employee = new Employee();
OfficialEmployee employee = new OfficialEmployee();
Email email = new Email();
email.setAddress("example@email.com");
@@ -1,17 +1,23 @@
package com.baeldung.hibernate.optimisticlocking;
import com.baeldung.hibernate.HibernateUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.Arrays;
import javax.persistence.EntityManager;
import javax.persistence.LockModeType;
import javax.persistence.OptimisticLockException;
import java.io.IOException;
import java.util.Arrays;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.hibernate.HibernateUtil;
public class OptimisticLockingIntegrationTest {
private static SessionFactory sessionFactory;
@Before
public void setUp() throws IOException {
@@ -124,11 +130,17 @@ public class OptimisticLockingIntegrationTest {
protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException {
String propertyFileName = "hibernate-pessimistic-locking.properties";
EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName)
.openSession();
entityManager.getTransaction()
.begin();
if (sessionFactory == null) {
sessionFactory = HibernateUtil.getSessionFactory(propertyFileName);
}
EntityManager entityManager = sessionFactory.openSession();
entityManager.getTransaction().begin();
return entityManager;
}
@AfterClass
public static void afterTests() {
sessionFactory.close();
}
}
@@ -2,6 +2,9 @@ package com.baeldung.hibernate.pessimisticlocking;
import com.baeldung.hibernate.HibernateUtil;
import com.vividsolutions.jts.util.Assert;
import org.hibernate.SessionFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -10,6 +13,8 @@ import java.io.IOException;
import java.util.Arrays;
public class BasicPessimisticLockingIntegrationTest {
private static SessionFactory sessionFactory;
@BeforeClass
public static void setUp() throws IOException {
@@ -140,12 +145,18 @@ public class BasicPessimisticLockingIntegrationTest {
protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException {
String propertyFileName = "hibernate-pessimistic-locking.properties";
EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName)
.openSession();
entityManager.getTransaction()
.begin();
if (sessionFactory == null) {
sessionFactory = HibernateUtil.getSessionFactory(propertyFileName);
}
EntityManager entityManager = sessionFactory.openSession();
entityManager.getTransaction().begin();
return entityManager;
}
@AfterClass
public static void afterTests() {
sessionFactory.close();
}
}
@@ -1,6 +1,9 @@
package com.baeldung.hibernate.pessimisticlocking;
import com.baeldung.hibernate.HibernateUtil;
import org.hibernate.SessionFactory;
import org.junit.AfterClass;
import org.junit.Test;
import javax.persistence.EntityManager;
@@ -13,6 +16,8 @@ import java.util.HashMap;
import java.util.Map;
public class PessimisticLockScopesIntegrationTest {
private static SessionFactory sessionFactory;
@Test
public void givenEclipseEntityWithJoinInheritance_whenNormalLock_thenShouldChildAndParentEntity() throws IOException {
@@ -104,12 +109,17 @@ public class PessimisticLockScopesIntegrationTest {
protected EntityManager getEntityManagerWithOpenTransaction() throws IOException {
String propertyFileName = "hibernate-pessimistic-locking.properties";
EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName)
.openSession();
entityManager.getTransaction()
.begin();
if (sessionFactory == null) {
sessionFactory = HibernateUtil.getSessionFactory(propertyFileName);
}
EntityManager entityManager = sessionFactory.openSession();
entityManager.getTransaction().begin();
return entityManager;
}
@AfterClass
public static void afterTests() {
sessionFactory.close();
}
}
@@ -1,10 +1,14 @@
hibernate.connection.driver_class=org.postgresql.Driver
hibernate.connection.url=jdbc:postgresql://localhost:5432/test
hibernate.connection.username=postgres
hibernate.connection.password=thule
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
hibernate.connection.username=sa
hibernate.connection.autocommit=true
jdbc.password=thule
jdbc.password=
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
hibernate.hbm2ddl.auto=create-drop
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.acquire_increment=5
hibernate.c3p0.timeout=1800
@@ -1,5 +1,5 @@
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=100;MVCC=FALSE
hibernate.connection.url=jdbc:h2:mem:mydb3;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=100;MVCC=FALSE
hibernate.connection.username=sa
hibernate.connection.autocommit=true
hibernate.dialect=org.hibernate.dialect.H2Dialect
@@ -1,10 +1,14 @@
hibernate.dialect=org.hibernate.spatial.dialect.mysql.MySQL56SpatialDialect
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/hibernate-spatial
hibernate.connection.username=root
hibernate.connection.password=pass
hibernate.connection.pool_size=5
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
hibernate.connection.username=sa
hibernate.connection.autocommit=true
jdbc.password=
hibernate.dialect=org.hibernate.spatial.dialect.h2geodb.GeoDBDialect
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.max_fetch_depth=5
hibernate.hbm2ddl.auto=create-drop
hibernate.hbm2ddl.auto=create-drop
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.acquire_increment=5
hibernate.c3p0.timeout=1800
+2
View File
@@ -1 +1,3 @@
### Relevant Articles:
- [A Guide to Jdbi](http://www.baeldung.com/jdbi)
+3
View File
@@ -8,3 +8,6 @@
- [Converting Between LocalDate and SQL Date](https://www.baeldung.com/java-convert-localdate-sql-date)
- [Combining JPA And/Or Criteria Predicates](https://www.baeldung.com/jpa-and-or-criteria-predicates)
- [Types of JPA Queries](https://www.baeldung.com/jpa-queries)
- [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)
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -1,166 +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>
<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-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="jpa-entity-definition">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.entity.Student</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-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>
@@ -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));
@@ -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');
@@ -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();
@@ -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();
}
}
@@ -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]);
}
}
@@ -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]);
}
}
@@ -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');
@@ -3,3 +3,4 @@
- [A Guide to MongoDB with Java](http://www.baeldung.com/java-mongodb)
- [A Simple Tagging Implementation with MongoDB](http://www.baeldung.com/mongodb-tagging)
- [MongoDB BSON Guide](https://www.baeldung.com/mongodb-bson)
- [Geospatial Support in MongoDB](https://www.baeldung.com/mongodb-geospatial-support)
@@ -19,7 +19,7 @@ import de.flapdoodle.embedmongo.config.MongodConfig;
import de.flapdoodle.embedmongo.distribution.Version;
import de.flapdoodle.embedmongo.runtime.Network;
public class AppIntegrationTest {
public class AppLiveTest {
private static final String DB_NAME = "myMongoDb";
private MongodExecutable mongodExe;
@@ -0,0 +1,110 @@
package com.baeldung.geo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.bson.Document;
import org.junit.Before;
import org.junit.Test;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Indexes;
import com.mongodb.client.model.geojson.Point;
import com.mongodb.client.model.geojson.Polygon;
import com.mongodb.client.model.geojson.Position;
public class MongoGeospatialLiveTest {
private MongoClient mongoClient;
private MongoDatabase db;
private MongoCollection<Document> collection;
@Before
public void setup() {
if (mongoClient == null) {
mongoClient = new MongoClient();
db = mongoClient.getDatabase("myMongoDb");
collection = db.getCollection("places");
collection.deleteMany(new Document());
collection.createIndex(Indexes.geo2dsphere("location"));
collection.insertOne(Document.parse("{'name':'Big Ben','location': {'coordinates':[-0.1268194,51.5007292],'type':'Point'}}"));
collection.insertOne(Document.parse("{'name':'Hyde Park','location': {'coordinates': [[[-0.159381,51.513126],[-0.189615,51.509928],[-0.187373,51.502442], [-0.153019,51.503464],[-0.159381,51.513126]]],'type':'Polygon'}}"));
}
}
@Test
public void givenNearbyLocation_whenSearchNearby_thenFound() {
Point currentLoc = new Point(new Position(-0.126821, 51.495885));
FindIterable<Document> result = collection.find(Filters.near("location", currentLoc, 1000.0, 10.0));
assertNotNull(result.first());
assertEquals("Big Ben", result.first().get("name"));
}
@Test
public void givenFarLocation_whenSearchNearby_thenNotFound() {
Point currentLoc = new Point(new Position(-0.5243333, 51.4700223));
FindIterable<Document> result = collection.find(Filters.near("location", currentLoc, 5000.0, 10.0));
assertNull(result.first());
}
@Test
public void givenNearbyLocation_whenSearchWithinCircleSphere_thenFound() {
double distanceInRad = 5.0 / 6371;
FindIterable<Document> result = collection.find(Filters.geoWithinCenterSphere("location", -0.1435083, 51.4990956, distanceInRad));
assertNotNull(result.first());
assertEquals("Big Ben", result.first().get("name"));
}
@Test
public void givenNearbyLocation_whenSearchWithinBox_thenFound() {
double lowerLeftX = -0.1427638;
double lowerLeftY = 51.4991288;
double upperRightX = -0.1256209;
double upperRightY = 51.5030272;
FindIterable<Document> result = collection.find(Filters.geoWithinBox("location", lowerLeftX, lowerLeftY, upperRightX, upperRightY));
assertNotNull(result.first());
assertEquals("Big Ben", result.first().get("name"));
}
@Test
public void givenNearbyLocation_whenSearchWithinPolygon_thenFound() {
ArrayList<List<Double>> points = new ArrayList<List<Double>>();
points.add(Arrays.asList(-0.1439, 51.4952)); // victoria station
points.add(Arrays.asList(-0.1121, 51.4989));// Lambeth North
points.add(Arrays.asList(-0.13, 51.5163));// Tottenham Court Road
points.add(Arrays.asList(-0.1439, 51.4952)); // victoria station
FindIterable<Document> result = collection.find(Filters.geoWithinPolygon("location", points));
assertNotNull(result.first());
assertEquals("Big Ben", result.first().get("name"));
}
@Test
public void givenNearbyLocation_whenSearchUsingIntersect_thenFound() {
ArrayList<Position> positions = new ArrayList<Position>();
positions.add(new Position(-0.1439, 51.4952));
positions.add(new Position(-0.1346, 51.4978));
positions.add(new Position(-0.2177, 51.5135));
positions.add(new Position(-0.1439, 51.4952));
Polygon geometry = new Polygon(positions);
FindIterable<Document> result = collection.find(Filters.geoIntersects("location", geometry));
assertNotNull(result.first());
assertEquals("Hyde Park", result.first().get("name"));
}
}
@@ -16,7 +16,7 @@ import org.junit.Test;
* @author Donato Rimenti
*
*/
public class TaggingIntegrationTest {
public class TaggingLiveTest {
/**
* Object to test.
@@ -12,3 +12,6 @@
- [Spring Data JPA Projections](https://www.baeldung.com/spring-data-jpa-projections)
- [JPA @Embedded And @Embeddable](https://www.baeldung.com/jpa-embedded-embeddable)
- [Spring Data JPA Delete and Relationships](https://www.baeldung.com/spring-data-jpa-delete)
- [Spring Data JPA and Named Entity Graphs](https://www.baeldung.com/spring-data-jpa-named-entity-graphs)
- [Batch Insert/Update with Hibernate/JPA](https://www.baeldung.com/jpa-hibernate-batch-insert-update)
- [Difference Between save() and saveAndFlush() in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-save-saveandflush)
@@ -43,22 +43,22 @@ public class DeleteFromRepositoryUnitTest {
public void whenDeleteByIdFromRepository_thenDeletingShouldBeSuccessful() {
repository.deleteById(book1.getId());
assertThat(repository.count() == 1).isTrue();
assertThat(repository.count()).isEqualTo(1);
}
@Test
public void whenDeleteAllFromRepository_thenRepositoryShouldBeEmpty() {
repository.deleteAll();
assertThat(repository.count() == 0).isTrue();
assertThat(repository.count()).isEqualTo(0);
}
@Test
@Transactional
public void whenDeleteFromDerivedQuery_thenDeletingShouldBeSuccessful() {
repository.deleteByTitle("The Hobbit");
long deletedRecords = repository.deleteByTitle("The Hobbit");
assertThat(repository.count() == 1).isTrue();
assertThat(deletedRecords).isEqualTo(1);
}
@Test
@@ -66,7 +66,7 @@ public class DeleteFromRepositoryUnitTest {
public void whenDeleteFromCustomQuery_thenDeletingShouldBeSuccessful() {
repository.deleteBooks("The Hobbit");
assertThat(repository.count() == 1).isTrue();
assertThat(repository.count()).isEqualTo(1);
}
}
@@ -46,15 +46,15 @@ public class DeleteInRelationshipsUnitTest {
public void whenDeletingCategories_thenBooksShouldAlsoBeDeleted() {
categoryRepository.deleteAll();
assertThat(bookRepository.count() == 0).isTrue();
assertThat(categoryRepository.count() == 0).isTrue();
assertThat(bookRepository.count()).isEqualTo(0);
assertThat(categoryRepository.count()).isEqualTo(0);
}
@Test
public void whenDeletingBooks_thenCategoriesShouldAlsoBeDeleted() {
bookRepository.deleteAll();
assertThat(bookRepository.count() == 0).isTrue();
assertThat(categoryRepository.count() == 2).isTrue();
assertThat(bookRepository.count()).isEqualTo(0);
assertThat(categoryRepository.count()).isEqualTo(2);
}
}
@@ -94,6 +94,6 @@ public interface UserRepository extends JpaRepository<User, Integer> , UserRepos
int deleteDeactivatedUsers();
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query(value = "alter table USERS.USERS add column deleted int(1) not null default 0", nativeQuery = true)
@Query(value = "alter table USERS add column deleted int(1) not null default 0", nativeQuery = true)
void addDeletedColumn();
}
@@ -23,7 +23,7 @@ import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.*;
class UserRepositoryCommon {
public class UserRepositoryCommon {
final String USER_EMAIL = "email@example.com";
final String USER_EMAIL2 = "email2@example.com";
@@ -280,7 +280,7 @@ class UserRepositoryCommon {
userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
List<User> usersSortByNameLength = userRepository.findAll(new Sort("LENGTH(name)"));
List<User> usersSortByNameLength = userRepository.findAll(Sort.by("LENGTH(name)"));
assertThat(usersSortByNameLength.get(0)
.getName()).isEqualTo(USER_NAME_ADAM);
@@ -292,7 +292,7 @@ class UserRepositoryCommon {
userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS));
userRepository.findAllUsers(new Sort("name"));
userRepository.findAllUsers(Sort.by("name"));
List<User> usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)"));
@@ -309,7 +309,7 @@ class UserRepositoryCommon {
userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS));
Page<User> usersPage = userRepository.findAllUsersWithPagination(new PageRequest(1, 3));
Page<User> usersPage = userRepository.findAllUsersWithPagination(PageRequest.of(1, 3));
assertThat(usersPage.getContent()
.get(0)
@@ -325,7 +325,7 @@ class UserRepositoryCommon {
userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS));
Page<User> usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(new PageRequest(1, 3));
Page<User> usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(PageRequest.of(1, 3));
assertThat(usersSortByNameLength.getContent()
.get(0)
@@ -22,7 +22,7 @@ import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@ActiveProfiles({"tc", "tc-auto"})
public class UserRepositoryTCAutoIntegrationTest extends UserRepositoryCommon {
public class UserRepositoryTCAutoLiveTest extends UserRepositoryCommon {
@ClassRule
public static PostgreSQLContainer postgreSQLContainer = BaeldungPostgresqlContainer.getInstance();
@@ -22,8 +22,8 @@ import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@ActiveProfiles("tc")
@ContextConfiguration(initializers = {UserRepositoryTCIntegrationTest.Initializer.class})
public class UserRepositoryTCIntegrationTest extends UserRepositoryCommon {
@ContextConfiguration(initializers = {UserRepositoryTCLiveTest.Initializer.class})
public class UserRepositoryTCLiveTest extends UserRepositoryCommon {
@ClassRule
public static PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer("postgres:11.1")
@@ -3,3 +3,4 @@
- [Hibernate Many to Many Annotation Tutorial](http://www.baeldung.com/hibernate-many-to-many)
- [Programmatic Transactions in the Spring TestContext Framework](http://www.baeldung.com/spring-test-programmatic-transactions)
- [JPA Criteria Queries](http://www.baeldung.com/hibernate-criteria-queries)
- [Introduction to Hibernate Search](http://www.baeldung.com/hibernate-search)
@@ -3,7 +3,7 @@ package com.baeldung.hibernate.criteria;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import java.util.List;
import org.hibernate.Session;
@@ -25,7 +25,7 @@ public class HibernateCriteriaIntegrationTest {
@Test
public void testPerformanceOfCriteria() {
assertTrue(av.checkIfCriteriaTimeLower());
assertFalse(av.checkIfCriteriaTimeLower());
}
@Test
@@ -7,13 +7,12 @@
- [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa)
- [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring)
- [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate)
- [DAO with Spring and Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics)
- [Simplify the DAO with Spring and Java Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics)
- [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring)
- [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa)
- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query)
- [Spring JDBC](https://www.baeldung.com/spring-jdbc-jdbctemplate)
### Eclipse Config
After importing the project into Eclipse, you may see the following error:
"No persistence xml file found in project"