JAVA-26042 | updated to spring-boot-3 (#14983)

This commit is contained in:
Gaetano Piazzolla 2023-10-22 14:40:23 +02:00 committed by GitHub
parent 6e470ca730
commit 193fa95e8c
18 changed files with 188 additions and 161 deletions

View File

@ -1,16 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>spring-data-jpa-query-2</artifactId> <artifactId>spring-data-jpa-query-2</artifactId>
<name>spring-data-jpa-query-2</name> <name>spring-data-jpa-query-2</name>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId> <artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath> <relativePath>../../parent-boot-3</relativePath>
</parent> </parent>
<dependencies> <dependencies>
@ -38,6 +38,7 @@
<dependency> <dependency>
<groupId>mysql</groupId> <groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId> <artifactId>mysql-connector-java</artifactId>
<version>3.1.12</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.google.guava</groupId> <groupId>com.google.guava</groupId>
@ -50,12 +51,19 @@
<version>${tomcat-dbcp.version}</version> <version>${tomcat-dbcp.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.hibernate</groupId> <groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId> <artifactId>hibernate-core</artifactId>
<version>6.3.1.Final</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.hibernate</groupId> <groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-envers</artifactId> <artifactId>hibernate-envers</artifactId>
<version>6.3.1.Final</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.13.0</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>

View File

@ -1,6 +1,6 @@
package com.baeldung.hibernate.fetching.model; package com.baeldung.hibernate.fetching.model;
import javax.persistence.*; import jakarta.persistence.*;
import java.io.Serializable; import java.io.Serializable;
import java.sql.Date; import java.sql.Date;

View File

@ -1,6 +1,6 @@
package com.baeldung.hibernate.fetching.model; package com.baeldung.hibernate.fetching.model;
import javax.persistence.*; import jakarta.persistence.*;
import java.io.Serializable; import java.io.Serializable;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;

View File

@ -1,6 +1,6 @@
package com.baeldung.hibernate.fetching.model; package com.baeldung.hibernate.fetching.model;
import javax.persistence.*; import jakarta.persistence.*;
import java.io.Serializable; import java.io.Serializable;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;

View File

@ -3,12 +3,12 @@ package com.baeldung.persistence.dao.common;
import java.io.Serializable; import java.io.Serializable;
import java.util.List; import java.util.List;
import javax.persistence.EntityManager; import jakarta.persistence.EntityManager;
import javax.persistence.PersistenceContext; import jakarta.persistence.PersistenceContext;
import javax.persistence.TypedQuery; import jakarta.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root; import jakarta.persistence.criteria.Root;
public class AbstractJpaDao<T extends Serializable> extends AbstractDao<T> implements IOperations<T> { public class AbstractJpaDao<T extends Serializable> extends AbstractDao<T> implements IOperations<T> {

View File

@ -3,29 +3,29 @@ package com.baeldung.persistence.model;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import org.hibernate.annotations.OrderBy; import org.hibernate.annotations.OrderBy;
import org.hibernate.envers.Audited; import org.hibernate.envers.Audited;
import org.jboss.logging.Logger;
import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener; import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.CascadeType; import jakarta.persistence.CascadeType;
import javax.persistence.Column; import jakarta.persistence.Column;
import javax.persistence.Entity; import jakarta.persistence.Entity;
import javax.persistence.EntityListeners; import jakarta.persistence.EntityListeners;
import javax.persistence.FetchType; import jakarta.persistence.FetchType;
import javax.persistence.GeneratedValue; import jakarta.persistence.GeneratedValue;
import javax.persistence.GenerationType; import jakarta.persistence.GenerationType;
import javax.persistence.Id; import jakarta.persistence.Id;
import javax.persistence.NamedQuery; import jakarta.persistence.NamedQuery;
import javax.persistence.OneToMany; import jakarta.persistence.OneToMany;
import javax.persistence.PrePersist; import jakarta.persistence.PrePersist;
import javax.persistence.PreRemove; import jakarta.persistence.PreRemove;
import javax.persistence.PreUpdate; import jakarta.persistence.PreUpdate;
import java.io.Serializable; import java.io.Serializable;
import java.util.Date; import java.util.Date;
import java.util.Set; import java.util.Set;
import java.util.logging.Logger;
@Entity @Entity
@NamedQuery(name = "Bar.findAll", query = "SELECT b FROM Bar b") @NamedQuery(name = "Bar.findAll", query = "SELECT b FROM Bar b")
@ -33,7 +33,7 @@ import java.util.Set;
@EntityListeners(AuditingEntityListener.class) @EntityListeners(AuditingEntityListener.class)
public class Bar implements Serializable { public class Bar implements Serializable {
private static final Logger LOGGER = Logger.getLogger(Bar.class); private static final Logger LOGGER = Logger.getLogger(Bar.class.toString());
public enum OPERATION { public enum OPERATION {
INSERT, UPDATE, DELETE; INSERT, UPDATE, DELETE;

View File

@ -2,10 +2,10 @@ package com.baeldung.persistence.model;
import java.io.Serializable; import java.io.Serializable;
import javax.persistence.Entity; import jakarta.persistence.Entity;
import javax.persistence.GeneratedValue; import jakarta.persistence.GeneratedValue;
import javax.persistence.Id; import jakarta.persistence.Id;
import javax.persistence.OneToOne; import jakarta.persistence.OneToOne;
@Entity @Entity
public class Child implements Serializable { public class Child implements Serializable {

View File

@ -2,20 +2,20 @@ package com.baeldung.persistence.model;
import java.io.Serializable; import java.io.Serializable;
import javax.persistence.CascadeType; import jakarta.persistence.CascadeType;
import javax.persistence.Column; import jakarta.persistence.Column;
import javax.persistence.Entity; import jakarta.persistence.Entity;
import javax.persistence.FetchType; import jakarta.persistence.FetchType;
import javax.persistence.GeneratedValue; import jakarta.persistence.GeneratedValue;
import javax.persistence.GenerationType; import jakarta.persistence.GenerationType;
import javax.persistence.Id; import jakarta.persistence.Id;
import javax.persistence.JoinColumn; import jakarta.persistence.JoinColumn;
import javax.persistence.ManyToOne; import jakarta.persistence.ManyToOne;
import javax.persistence.NamedNativeQueries; import jakarta.persistence.NamedNativeQueries;
import javax.persistence.NamedNativeQuery; import jakarta.persistence.NamedNativeQuery;
import javax.persistence.NamedStoredProcedureQuery; import jakarta.persistence.NamedStoredProcedureQuery;
import javax.persistence.ParameterMode; import jakarta.persistence.ParameterMode;
import javax.persistence.StoredProcedureParameter; import jakarta.persistence.StoredProcedureParameter;
import org.hibernate.envers.Audited; import org.hibernate.envers.Audited;

View File

@ -2,12 +2,12 @@ package com.baeldung.persistence.model;
import java.io.Serializable; import java.io.Serializable;
import javax.persistence.CascadeType; import jakarta.persistence.CascadeType;
import javax.persistence.Entity; import jakarta.persistence.Entity;
import javax.persistence.GeneratedValue; import jakarta.persistence.GeneratedValue;
import javax.persistence.Id; import jakarta.persistence.Id;
import javax.persistence.JoinColumn; import jakarta.persistence.JoinColumn;
import javax.persistence.OneToOne; import jakarta.persistence.OneToOne;
@Entity @Entity
public class Parent implements Serializable { public class Parent implements Serializable {

View File

@ -1,8 +1,8 @@
package com.baeldung.persistence.model; package com.baeldung.persistence.model;
import javax.persistence.Entity; import jakarta.persistence.Entity;
import javax.persistence.GeneratedValue; import jakarta.persistence.GeneratedValue;
import javax.persistence.Id; import jakarta.persistence.Id;
@Entity @Entity
public class Person { public class Person {

View File

@ -1,6 +1,6 @@
package com.baeldung.spring.data.jpa.query; package com.baeldung.spring.data.jpa.query;
import javax.persistence.*; import jakarta.persistence.*;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;

View File

@ -1,8 +1,8 @@
package com.baeldung.spring.data.jpa.query; package com.baeldung.spring.data.jpa.query;
import javax.persistence.EntityManager; import jakarta.persistence.EntityManager;
import javax.persistence.PersistenceContext; import jakarta.persistence.PersistenceContext;
import javax.persistence.criteria.*; import jakarta.persistence.criteria.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;

View File

@ -4,8 +4,8 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import javax.persistence.EntityManager; import jakarta.persistence.EntityManager;
import javax.persistence.EntityManagerFactory; import jakarta.persistence.EntityManagerFactory;
import org.junit.After; import org.junit.After;
import org.junit.AfterClass; import org.junit.AfterClass;
@ -30,15 +30,15 @@ import com.baeldung.spring.config.PersistenceTestConfig;
@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) @ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
public class JPABarAuditIntegrationTest { public class JPABarAuditIntegrationTest {
private static Logger logger = LoggerFactory.getLogger(JPABarAuditIntegrationTest.class); private static final Logger logger = LoggerFactory.getLogger(JPABarAuditIntegrationTest.class);
@BeforeClass @BeforeClass
public static void setUpBeforeClass() throws Exception { public static void setUpBeforeClass() {
logger.info("setUpBeforeClass()"); logger.info("setUpBeforeClass()");
} }
@AfterClass @AfterClass
public static void tearDownAfterClass() throws Exception { public static void tearDownAfterClass(){
logger.info("tearDownAfterClass()"); logger.info("tearDownAfterClass()");
} }

View File

@ -3,8 +3,8 @@ package com.baeldung.persistence.audit;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import javax.persistence.EntityManager; import jakarta.persistence.EntityManager;
import javax.persistence.EntityManagerFactory; import jakarta.persistence.EntityManagerFactory;
import org.junit.After; import org.junit.After;
import org.junit.AfterClass; import org.junit.AfterClass;
@ -29,7 +29,7 @@ import com.baeldung.spring.config.PersistenceTestConfig;
@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) @ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
public class SpringDataJPABarAuditIntegrationTest { public class SpringDataJPABarAuditIntegrationTest {
private static Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditIntegrationTest.class); private static final Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditIntegrationTest.class);
@BeforeClass @BeforeClass
public static void setUpBeforeClass() throws Exception { public static void setUpBeforeClass() throws Exception {
@ -37,7 +37,7 @@ public class SpringDataJPABarAuditIntegrationTest {
} }
@AfterClass @AfterClass
public static void tearDownAfterClass() throws Exception { public static void tearDownAfterClass(){
logger.info("tearDownAfterClass()"); logger.info("tearDownAfterClass()");
} }

View File

@ -17,7 +17,7 @@ public class FooFixtures {
private static final Logger LOGGER = LoggerFactory.getLogger(FooFixtures.class); private static final Logger LOGGER = LoggerFactory.getLogger(FooFixtures.class);
private SessionFactory sessionFactory; private final SessionFactory sessionFactory;
public FooFixtures(final SessionFactory sessionFactory) { public FooFixtures(final SessionFactory sessionFactory) {
super(); super();
@ -28,8 +28,8 @@ public class FooFixtures {
// API // API
public void createBars() { public void createBars() {
Session session = null; Session session;
Transaction tx = null; Transaction tx;
session = sessionFactory.openSession(); session = sessionFactory.openSession();
tx = session.getTransaction(); tx = session.getTransaction();
try { try {
@ -39,13 +39,13 @@ public class FooFixtures {
bar.setName("Bar_" + i); bar.setName("Bar_" + i);
final Foo foo = new Foo("Foo_" + (i + 120)); final Foo foo = new Foo("Foo_" + (i + 120));
foo.setBar(bar); foo.setBar(bar);
session.save(foo); session.persist(foo);
final Foo foo2 = new Foo(null); final Foo foo2 = new Foo(null);
if (i % 2 == 0) { if (i % 2 == 0) {
foo2.setName("LuckyFoo" + (i + 120)); foo2.setName("LuckyFoo" + (i + 120));
} }
foo2.setBar(bar); foo2.setBar(bar);
session.save(foo2); session.persist(foo2);
bar.getFooSet().add(foo); bar.getFooSet().add(foo);
bar.getFooSet().add(foo2); bar.getFooSet().add(foo2);
session.merge(bar); session.merge(bar);
@ -53,16 +53,12 @@ public class FooFixtures {
tx.commit(); tx.commit();
session.flush(); session.flush();
} catch (final HibernateException he) { } catch (final HibernateException he) {
if (tx != null) { tx.rollback();
tx.rollback();
}
LOGGER.error("Not able to open session", he); LOGGER.error("Not able to open session", he);
} catch (final Exception e) { } catch (final Exception e) {
LOGGER.error(e.getLocalizedMessage(), e); LOGGER.error(e.getLocalizedMessage(), e);
} finally { } finally {
if (session != null) { session.close();
session.close();
}
} }
} }
@ -86,23 +82,18 @@ public class FooFixtures {
try { try {
tx.begin(); tx.begin();
for (final Foo foo : fooList) { for (final Foo foo : fooList) {
session.persist(foo.getBar());
session.save(foo.getBar()); session.persist(foo);
session.save(foo);
} }
tx.commit(); tx.commit();
session.flush(); session.flush();
} catch (final HibernateException he) { } catch (final HibernateException he) {
if (tx != null) { tx.rollback();
tx.rollback();
}
LOGGER.error("Not able to open session", he); LOGGER.error("Not able to open session", he);
} catch (final Exception e) { } catch (final Exception e) {
LOGGER.error(e.getLocalizedMessage(), e); LOGGER.error(e.getLocalizedMessage(), e);
} finally { } finally {
if (session != null) { session.close();
session.close();
}
} }
} }

View File

@ -1,19 +1,19 @@
package com.baeldung.persistence.hibernate; package com.baeldung.persistence.hibernate;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertThat;
import java.util.List; import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.ScrollMode; import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults; import org.hibernate.ScrollableResults;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections; import org.hibernate.query.Query;
import org.hibernate.query.SelectionQuery;
import org.hibernate.query.criteria.HibernateCriteriaBuilder;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -28,6 +28,8 @@ import com.baeldung.persistence.service.IFooService;
import com.baeldung.spring.config.PersistenceTestConfig; import com.baeldung.spring.config.PersistenceTestConfig;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import jakarta.persistence.criteria.CriteriaQuery;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) @ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
public class FooPaginationPersistenceIntegrationTest { public class FooPaginationPersistenceIntegrationTest {
@ -40,8 +42,6 @@ public class FooPaginationPersistenceIntegrationTest {
private Session session; private Session session;
// tests
@Before @Before
public final void before() { public final void before() {
final int minimalNumberOfEntities = 25; final int minimalNumberOfEntities = 25;
@ -59,20 +59,17 @@ public class FooPaginationPersistenceIntegrationTest {
session.close(); session.close();
} }
// tests
@Test @Test
public final void whenContextIsBootstrapped_thenNoExceptions() { public final void whenContextIsBootstrapped_thenNoExceptions() {
// //
} }
@SuppressWarnings("unchecked")
@Test @Test
public final void whenRetrievingPaginatedEntities_thenCorrectSize() { public final void whenRetrievingPaginatedEntities_thenCorrectSize() {
final int pageNumber = 1; final int pageNumber = 1;
final int pageSize = 10; final int pageSize = 10;
final Query query = session.createQuery("From Foo"); final Query<Foo> query = session.createQuery("From Foo",Foo.class);
query.setFirstResult((pageNumber - 1) * pageSize); query.setFirstResult((pageNumber - 1) * pageSize);
query.setMaxResults(pageSize); query.setMaxResults(pageSize);
final List<Foo> fooList = query.list(); final List<Foo> fooList = query.list();
@ -80,19 +77,18 @@ public class FooPaginationPersistenceIntegrationTest {
assertThat(fooList, hasSize(pageSize)); assertThat(fooList, hasSize(pageSize));
} }
@SuppressWarnings("unchecked")
@Test @Test
public final void whenRetrievingAllPages_thenCorrect() { public final void whenRetrievingAllPages_thenCorrect() {
int pageNumber = 1; int pageNumber = 1;
final int pageSize = 10; final int pageSize = 10;
final String countQ = "Select count (f.id) from Foo f"; final String countQ = "Select count (f.id) from Foo f";
final Query countQuery = session.createQuery(countQ); final Query<Long> countQuery = session.createQuery(countQ, Long.class);
final Long countResult = (Long) countQuery.uniqueResult(); final Long countResult = (Long) countQuery.uniqueResult();
final List<Foo> fooList = Lists.newArrayList(); final List<Foo> fooList = Lists.newArrayList();
int totalEntities = 0; int totalEntities = 0;
final Query query = session.createQuery("From Foo"); final Query<Foo> query = session.createQuery("From Foo", Foo.class);
while (totalEntities < countResult) { while (totalEntities < countResult) {
query.setFirstResult((pageNumber - 1) * pageSize); query.setFirstResult((pageNumber - 1) * pageSize);
query.setMaxResults(pageSize); query.setMaxResults(pageSize);
@ -102,17 +98,16 @@ public class FooPaginationPersistenceIntegrationTest {
} }
} }
@SuppressWarnings("unchecked")
@Test @Test
public final void whenRetrievingLastPage_thenCorrectSize() { public final void whenRetrievingLastPage_thenCorrectSize() {
final int pageSize = 10; final int pageSize = 10;
final String countQ = "Select count (f.id) from Foo f"; final String countQ = "Select count (f.id) from Foo f";
final Query countQuery = session.createQuery(countQ); final Query<Long> countQuery = session.createQuery(countQ, Long.class);
final Long countResults = (Long) countQuery.uniqueResult(); final Long countResults = countQuery.uniqueResult();
final int lastPageNumber = (int) (Math.ceil(countResults / pageSize)); final int lastPageNumber = (int) (Math.ceil(countResults / pageSize));
final Query selectQuery = session.createQuery("From Foo"); final Query<Foo> selectQuery = session.createQuery("From Foo",Foo.class);
selectQuery.setFirstResult((lastPageNumber - 1) * pageSize); selectQuery.setFirstResult((lastPageNumber - 1) * pageSize);
selectQuery.setMaxResults(pageSize); selectQuery.setMaxResults(pageSize);
final List<Foo> lastPage = selectQuery.list(); final List<Foo> lastPage = selectQuery.list();
@ -126,9 +121,9 @@ public class FooPaginationPersistenceIntegrationTest {
public final void givenUsingTheScrollableApi_whenRetrievingPaginatedData_thenCorrect() { public final void givenUsingTheScrollableApi_whenRetrievingPaginatedData_thenCorrect() {
final int pageSize = 10; final int pageSize = 10;
final String hql = "FROM Foo f order by f.name"; final String hql = "FROM Foo f order by f.name";
final Query query = session.createQuery(hql); final Query<Foo> query = session.createQuery(hql,Foo.class);
final ScrollableResults resultScroll = query.scroll(ScrollMode.FORWARD_ONLY); final ScrollableResults<Foo> resultScroll = query.scroll(ScrollMode.FORWARD_ONLY);
// resultScroll.last(); // resultScroll.last();
// final int totalResults = resultScroll.getRowNumber() + 1; // final int totalResults = resultScroll.getRowNumber() + 1;
@ -138,7 +133,7 @@ public class FooPaginationPersistenceIntegrationTest {
final List<Foo> fooPage = Lists.newArrayList(); final List<Foo> fooPage = Lists.newArrayList();
int i = 0; int i = 0;
while (pageSize > i++) { while (pageSize > i++) {
fooPage.add((Foo) resultScroll.get(0)); fooPage.add((Foo) resultScroll.get());
if (!resultScroll.next()) { if (!resultScroll.next()) {
break; break;
} }
@ -147,36 +142,42 @@ public class FooPaginationPersistenceIntegrationTest {
assertThat(fooPage, hasSize(lessThan(10 + 1))); assertThat(fooPage, hasSize(lessThan(10 + 1)));
} }
@SuppressWarnings("unchecked")
@Test @Test
public final void givenUsingTheCriteriaApi_whenRetrievingFirstPage_thenCorrect() { public final void givenUsingTheCriteriaApi_whenRetrievingFirstPage_thenCorrect() {
final int pageSize = 10; final int pageSize = 10;
final Criteria criteria = session.createCriteria(Foo.class); CriteriaQuery<Foo> selectQuery = session.getCriteriaBuilder().createQuery(Foo.class);
criteria.setFirstResult(0); selectQuery.from(Foo.class);
criteria.setMaxResults(pageSize);
final List<Foo> firstPage = criteria.list(); SelectionQuery<Foo> query = session.createQuery(selectQuery);
query.setFirstResult(0);
query.setMaxResults(pageSize);
final List<Foo> firstPage = query.list();
assertThat(firstPage, hasSize(pageSize)); assertThat(firstPage, hasSize(pageSize));
} }
@SuppressWarnings("unchecked")
@Test @Test
public final void givenUsingTheCriteriaApi_whenRetrievingPaginatedData_thenCorrect() { public final void givenUsingTheCriteriaApi_whenRetrievingPaginatedData_thenCorrect() {
final Criteria criteriaCount = session.createCriteria(Foo.class);
criteriaCount.setProjection(Projections.rowCount()); HibernateCriteriaBuilder qb = session.getCriteriaBuilder();
final Long count = (Long) criteriaCount.uniqueResult(); CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(Foo.class)));
final Long count = session.createQuery(cq).getSingleResult();
int pageNumber = 1; int pageNumber = 1;
final int pageSize = 10; final int pageSize = 10;
final List<Foo> fooList = Lists.newArrayList(); final List<Foo> fooList = Lists.newArrayList();
final Criteria criteria = session.createCriteria(Foo.class); CriteriaQuery<Foo> selectQuery = session.getCriteriaBuilder().createQuery(Foo.class);
selectQuery.from(Foo.class);
SelectionQuery<Foo> query = session.createQuery(selectQuery);
int totalEntities = 0; int totalEntities = 0;
while (totalEntities < count.intValue()) { while (totalEntities < count.intValue()) {
criteria.setFirstResult((pageNumber - 1) * pageSize); query.setFirstResult((pageNumber - 1) * pageSize);
criteria.setMaxResults(pageSize); query.setMaxResults(pageSize);
fooList.addAll(criteria.list()); fooList.addAll(query.list());
totalEntities = fooList.size(); totalEntities = fooList.size();
pageNumber++; pageNumber++;
} }

View File

@ -2,15 +2,17 @@ package com.baeldung.persistence.hibernate;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import org.hibernate.Criteria;
import org.hibernate.NullPrecedence;
import org.hibernate.Query;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order; import org.hibernate.query.NullPrecedence;
import org.hibernate.query.Order;
import org.hibernate.query.Query;
import org.hibernate.query.SortDirection;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -26,6 +28,8 @@ import com.baeldung.persistence.model.Bar;
import com.baeldung.persistence.model.Foo; import com.baeldung.persistence.model.Foo;
import com.baeldung.spring.config.PersistenceTestConfig; import com.baeldung.spring.config.PersistenceTestConfig;
import jakarta.persistence.criteria.CriteriaQuery;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) @ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -91,7 +95,7 @@ public class FooSortingPersistenceIntegrationTest {
@Test @Test
public final void whenHQlSortingByOneAttribute_andOrderDirection_thenPrintSortedResults() { public final void whenHQlSortingByOneAttribute_andOrderDirection_thenPrintSortedResults() {
final String hql = "FROM Foo f ORDER BY f.name ASC"; final String hql = "FROM Foo f ORDER BY f.name ASC";
final Query query = session.createQuery(hql); Query<Foo> query = session.createQuery(hql, Foo.class);
final List<Foo> fooList = query.list(); final List<Foo> fooList = query.list();
for (final Foo foo : fooList) { for (final Foo foo : fooList) {
LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId()); LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId());
@ -101,7 +105,7 @@ public class FooSortingPersistenceIntegrationTest {
@Test @Test
public final void whenHQlSortingByMultipleAttributes_thenSortedResults() { public final void whenHQlSortingByMultipleAttributes_thenSortedResults() {
final String hql = "FROM Foo f ORDER BY f.name, f.id"; final String hql = "FROM Foo f ORDER BY f.name, f.id";
final Query query = session.createQuery(hql); Query<Foo> query = session.createQuery(hql, Foo.class);
final List<Foo> fooList = query.list(); final List<Foo> fooList = query.list();
for (final Foo foo : fooList) { for (final Foo foo : fooList) {
LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId()); LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId());
@ -111,7 +115,7 @@ public class FooSortingPersistenceIntegrationTest {
@Test @Test
public final void whenHQlSortingByMultipleAttributes_andOrderDirection_thenPrintSortedResults() { public final void whenHQlSortingByMultipleAttributes_andOrderDirection_thenPrintSortedResults() {
final String hql = "FROM Foo f ORDER BY f.name DESC, f.id ASC"; final String hql = "FROM Foo f ORDER BY f.name DESC, f.id ASC";
final Query query = session.createQuery(hql); Query<Foo> query = session.createQuery(hql, Foo.class);
final List<Foo> fooList = query.list(); final List<Foo> fooList = query.list();
for (final Foo foo : fooList) { for (final Foo foo : fooList) {
LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId()); LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId());
@ -120,9 +124,12 @@ public class FooSortingPersistenceIntegrationTest {
@Test @Test
public final void whenHQLCriteriaSortingByOneAttr_thenPrintSortedResults() { public final void whenHQLCriteriaSortingByOneAttr_thenPrintSortedResults() {
final Criteria criteria = session.createCriteria(Foo.class, "FOO"); CriteriaQuery<Foo> selectQuery = session.getCriteriaBuilder().createQuery(Foo.class);
criteria.addOrder(Order.asc("id")); selectQuery.from(Foo.class);
final List<Foo> fooList = criteria.list(); Query<Foo> query = session.createQuery(selectQuery);
query.setOrder(Collections.singletonList(Order.asc(Foo.class,"id")));
final List<Foo> fooList = query.list();
for (final Foo foo : fooList) { for (final Foo foo : fooList) {
LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName()); LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName());
} }
@ -130,10 +137,16 @@ public class FooSortingPersistenceIntegrationTest {
@Test @Test
public final void whenHQLCriteriaSortingByMultipAttr_thenSortedResults() { public final void whenHQLCriteriaSortingByMultipAttr_thenSortedResults() {
final Criteria criteria = session.createCriteria(Foo.class, "FOO");
criteria.addOrder(Order.asc("name")); CriteriaQuery<Foo> selectQuery = session.getCriteriaBuilder().createQuery(Foo.class);
criteria.addOrder(Order.asc("id")); selectQuery.from(Foo.class);
final List<Foo> fooList = criteria.list(); Query<Foo> query = session.createQuery(selectQuery);
List<Order<? super Foo>> orderBy = new ArrayList<>(2);
orderBy.add(Order.asc(Foo.class,"name"));
orderBy.add(Order.asc(Foo.class,"id"));
query.setOrder(orderBy);
final List<Foo> fooList = query.list();
for (final Foo foo : fooList) { for (final Foo foo : fooList) {
LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName()); LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName());
} }
@ -141,9 +154,15 @@ public class FooSortingPersistenceIntegrationTest {
@Test @Test
public final void whenCriteriaSortingStringNullsLastAsc_thenNullsLast() { public final void whenCriteriaSortingStringNullsLastAsc_thenNullsLast() {
final Criteria criteria = session.createCriteria(Foo.class, "FOO"); CriteriaQuery<Foo> selectQuery = session.getCriteriaBuilder().createQuery(Foo.class);
criteria.addOrder(Order.asc("name").nulls(NullPrecedence.LAST)); selectQuery.from(Foo.class);
final List<Foo> fooList = criteria.list(); Query<Foo> query = session.createQuery(selectQuery);
List<Order<? super Foo>> orderBy = new ArrayList<>(2);
orderBy.add(Order.by(Foo.class,"name", SortDirection.ASCENDING, NullPrecedence.LAST));
query.setOrder(orderBy);
final List<Foo> fooList = query.list();
assertNull(fooList.get(fooList.toArray().length - 1).getName()); assertNull(fooList.get(fooList.toArray().length - 1).getName());
for (final Foo foo : fooList) { for (final Foo foo : fooList) {
LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName()); LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName());
@ -152,9 +171,15 @@ public class FooSortingPersistenceIntegrationTest {
@Test @Test
public final void whenCriteriaSortingStringNullsFirstDesc_thenNullsFirst() { public final void whenCriteriaSortingStringNullsFirstDesc_thenNullsFirst() {
final Criteria criteria = session.createCriteria(Foo.class, "FOO"); CriteriaQuery<Foo> selectQuery = session.getCriteriaBuilder().createQuery(Foo.class);
criteria.addOrder(Order.desc("name").nulls(NullPrecedence.FIRST)); selectQuery.from(Foo.class);
final List<Foo> fooList = criteria.list(); Query<Foo> query = session.createQuery(selectQuery);
List<Order<? super Foo>> orderBy = new ArrayList<>(2);
orderBy.add(Order.by(Foo.class,"name", SortDirection.ASCENDING, NullPrecedence.FIRST));
query.setOrder(orderBy);
final List<Foo> fooList = query.list();
assertNull(fooList.get(0).getName()); assertNull(fooList.get(0).getName());
for (final Foo foo : fooList) { for (final Foo foo : fooList) {
LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName()); LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName());
@ -164,7 +189,7 @@ public class FooSortingPersistenceIntegrationTest {
@Test @Test
public final void whenSortingBars_thenBarsWithSortedFoos() { public final void whenSortingBars_thenBarsWithSortedFoos() {
final String hql = "FROM Bar b ORDER BY b.id"; final String hql = "FROM Bar b ORDER BY b.id";
final Query query = session.createQuery(hql); final Query<Bar> query = session.createQuery(hql, Bar.class);
final List<Bar> barList = query.list(); final List<Bar> barList = query.list();
for (final Bar bar : barList) { for (final Bar bar : barList) {
final Set<Foo> fooSet = bar.getFooSet(); final Set<Foo> fooSet = bar.getFooSet();

View File

@ -5,14 +5,14 @@ import static org.junit.Assert.assertEquals;
import java.util.List; import java.util.List;
import javax.persistence.EntityManager; import jakarta.persistence.EntityManager;
import javax.persistence.EntityManagerFactory; import jakarta.persistence.EntityManagerFactory;
import javax.persistence.StoredProcedureQuery; import jakarta.persistence.StoredProcedureQuery;
import org.hibernate.Query;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.hibernate.exception.SQLGrammarException; import org.hibernate.exception.SQLGrammarException;
import org.hibernate.query.Query;
import org.junit.After; import org.junit.After;
import org.junit.Assume; import org.junit.Assume;
import org.junit.Before; import org.junit.Before;
@ -59,22 +59,22 @@ public class FooStoredProceduresLiveTest {
private boolean getFoosByNameExists() { private boolean getFoosByNameExists() {
try { try {
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); Query<Foo> sqlQuery = session.createNativeQuery("CALL GetFoosByName()",Foo.class);
sqlQuery.list(); sqlQuery.list();
return true; return true;
} catch (SQLGrammarException e) { } catch (SQLGrammarException e) {
LOGGER.error("WARNING : GetFoosByName() Procedure is may be missing ", e); LOGGER.error("WARNING : GetFoosByName() Procedure may be missing ", e);
return false; return false;
} }
} }
private boolean getAllFoosExists() { private boolean getAllFoosExists() {
try { try {
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); Query<Foo> sqlQuery = session.createNativeQuery("CALL GetAllFoos()",Foo.class);
sqlQuery.list(); sqlQuery.list();
return true; return true;
} catch (SQLGrammarException e) { } catch (SQLGrammarException e) {
LOGGER.error("WARNING : GetAllFoos() Procedure is may be missing ", e); LOGGER.error("WARNING : GetAllFoos() Procedure may be missing ", e);
return false; return false;
} }
} }
@ -90,9 +90,9 @@ public class FooStoredProceduresLiveTest {
fooService.create(new Foo(randomAlphabetic(6))); fooService.create(new Foo(randomAlphabetic(6)));
// Stored procedure getAllFoos using createSQLQuery // Stored procedure getAllFoos using createQuery
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); Query<Foo> sqlQuery = session.createNativeQuery("CALL GetAllFoos()", Foo.class);
@SuppressWarnings("unchecked")
List<Foo> allFoos = sqlQuery.list(); List<Foo> allFoos = sqlQuery.list();
for (Foo foo : allFoos) { for (Foo foo : allFoos) {
LOGGER.info("getAllFoos() SQL Query result : {}", foo.getName()); LOGGER.info("getAllFoos() SQL Query result : {}", foo.getName());
@ -100,8 +100,8 @@ public class FooStoredProceduresLiveTest {
assertEquals(allFoos.size(), fooService.findAll().size()); assertEquals(allFoos.size(), fooService.findAll().size());
// Stored procedure getAllFoos using a Named Query // Stored procedure getAllFoos using a Named Query
Query namedQuery = session.getNamedQuery("callGetAllFoos"); Query<Foo> namedQuery = session.createNamedQuery("callGetAllFoos", Foo.class);
@SuppressWarnings("unchecked")
List<Foo> allFoos2 = namedQuery.list(); List<Foo> allFoos2 = namedQuery.list();
for (Foo foo : allFoos2) { for (Foo foo : allFoos2) {
LOGGER.info("getAllFoos() NamedQuery result : {}", foo.getName()); LOGGER.info("getAllFoos() NamedQuery result : {}", foo.getName());
@ -110,6 +110,7 @@ public class FooStoredProceduresLiveTest {
StoredProcedureQuery spQuery = StoredProcedureQuery spQuery =
entityManager.createNamedStoredProcedureQuery("GetAllFoos"); entityManager.createNamedStoredProcedureQuery("GetAllFoos");
@SuppressWarnings("unchecked")
List<Foo> allFoos3 = spQuery.getResultList(); List<Foo> allFoos3 = spQuery.getResultList();
for (Foo foo : allFoos3) { for (Foo foo : allFoos3) {
LOGGER.info("getAllFoos() StoredProcedureQuery result : {}", foo.getName()); LOGGER.info("getAllFoos() StoredProcedureQuery result : {}", foo.getName());
@ -124,16 +125,16 @@ public class FooStoredProceduresLiveTest {
fooService.create(new Foo("NewFooName")); fooService.create(new Foo("NewFooName"));
// Stored procedure getFoosByName using createSQLQuery() // Stored procedure getFoosByName using createSQLQuery()
Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)").addEntity(Foo.class).setParameter("fooName", "NewFooName"); Query<Foo> sqlQuery = session.createNativeQuery("CALL GetFoosByName(:fooName)", Foo.class).setParameter("fooName", "NewFooName");
@SuppressWarnings("unchecked")
List<Foo> allFoosByName = sqlQuery.list(); List<Foo> allFoosByName = sqlQuery.list();
for (Foo foo : allFoosByName) { for (Foo foo : allFoosByName) {
LOGGER.info("getFoosByName() using SQL Query : found => {}", foo.toString()); LOGGER.info("getFoosByName() using SQL Query : found => {}", foo.toString());
} }
// Stored procedure getFoosByName using getNamedQuery() // Stored procedure getFoosByName using getNamedQuery()
Query namedQuery = session.getNamedQuery("callGetFoosByName").setParameter("fooName", "NewFooName"); Query<Foo> namedQuery = session.createQuery("callGetFoosByName", Foo.class).setParameter("fooName", "NewFooName");
@SuppressWarnings("unchecked")
List<Foo> allFoosByName2 = namedQuery.list(); List<Foo> allFoosByName2 = namedQuery.list();
for (Foo foo : allFoosByName2) { for (Foo foo : allFoosByName2) {
LOGGER.info("getFoosByName() using Native Query : found => {}", foo.toString()); LOGGER.info("getFoosByName() using Native Query : found => {}", foo.toString());
@ -142,6 +143,7 @@ public class FooStoredProceduresLiveTest {
StoredProcedureQuery spQuery = entityManager. StoredProcedureQuery spQuery = entityManager.
createNamedStoredProcedureQuery("GetFoosByName") createNamedStoredProcedureQuery("GetFoosByName")
.setParameter("fooName", "NewFooName"); .setParameter("fooName", "NewFooName");
@SuppressWarnings("unchecked")
List<Foo> allFoosByName3 = spQuery.getResultList(); List<Foo> allFoosByName3 = spQuery.getResultList();
assertEquals(1, allFoosByName3.size()); assertEquals(1, allFoosByName3.size());
for (Foo foo : allFoosByName3) { for (Foo foo : allFoosByName3) {