JAVA-26042 | updated to spring-boot-3 (#14983)
This commit is contained in:
parent
6e470ca730
commit
193fa95e8c
|
@ -1,16 +1,16 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
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">
|
||||
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">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>spring-data-jpa-query-2</artifactId>
|
||||
<name>spring-data-jpa-query-2</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<artifactId>parent-boot-3</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
<relativePath>../../parent-boot-3</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
@ -38,6 +38,7 @@
|
|||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>3.1.12</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
|
@ -50,12 +51,19 @@
|
|||
<version>${tomcat-dbcp.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<groupId>org.hibernate.orm</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>6.3.1.Final</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<groupId>org.hibernate.orm</groupId>
|
||||
<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>
|
||||
<groupId>org.springframework</groupId>
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
package com.baeldung.hibernate.fetching.model;
|
||||
|
||||
import javax.persistence.*;
|
||||
import jakarta.persistence.*;
|
||||
import java.io.Serializable;
|
||||
import java.sql.Date;
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
package com.baeldung.hibernate.fetching.model;
|
||||
|
||||
import javax.persistence.*;
|
||||
import jakarta.persistence.*;
|
||||
import java.io.Serializable;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
package com.baeldung.hibernate.fetching.model;
|
||||
|
||||
import javax.persistence.*;
|
||||
import jakarta.persistence.*;
|
||||
import java.io.Serializable;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
|
|
@ -3,12 +3,12 @@ package com.baeldung.persistence.dao.common;
|
|||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.persistence.TypedQuery;
|
||||
import javax.persistence.criteria.CriteriaBuilder;
|
||||
import javax.persistence.criteria.CriteriaQuery;
|
||||
import javax.persistence.criteria.Root;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.PersistenceContext;
|
||||
import jakarta.persistence.TypedQuery;
|
||||
import jakarta.persistence.criteria.CriteriaBuilder;
|
||||
import jakarta.persistence.criteria.CriteriaQuery;
|
||||
import jakarta.persistence.criteria.Root;
|
||||
|
||||
public class AbstractJpaDao<T extends Serializable> extends AbstractDao<T> implements IOperations<T> {
|
||||
|
||||
|
|
|
@ -3,29 +3,29 @@ package com.baeldung.persistence.model;
|
|||
import com.google.common.collect.Sets;
|
||||
import org.hibernate.annotations.OrderBy;
|
||||
import org.hibernate.envers.Audited;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.springframework.data.annotation.CreatedBy;
|
||||
import org.springframework.data.annotation.CreatedDate;
|
||||
import org.springframework.data.annotation.LastModifiedBy;
|
||||
import org.springframework.data.annotation.LastModifiedDate;
|
||||
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
|
||||
import javax.persistence.CascadeType;
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.EntityListeners;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.NamedQuery;
|
||||
import javax.persistence.OneToMany;
|
||||
import javax.persistence.PrePersist;
|
||||
import javax.persistence.PreRemove;
|
||||
import javax.persistence.PreUpdate;
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.EntityListeners;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.NamedQuery;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.PreRemove;
|
||||
import jakarta.persistence.PreUpdate;
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@Entity
|
||||
@NamedQuery(name = "Bar.findAll", query = "SELECT b FROM Bar b")
|
||||
|
@ -33,7 +33,7 @@ import java.util.Set;
|
|||
@EntityListeners(AuditingEntityListener.class)
|
||||
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 {
|
||||
INSERT, UPDATE, DELETE;
|
||||
|
|
|
@ -2,10 +2,10 @@ package com.baeldung.persistence.model;
|
|||
|
||||
import java.io.Serializable;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.OneToOne;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.OneToOne;
|
||||
|
||||
@Entity
|
||||
public class Child implements Serializable {
|
||||
|
|
|
@ -2,20 +2,20 @@ package com.baeldung.persistence.model;
|
|||
|
||||
import java.io.Serializable;
|
||||
|
||||
import javax.persistence.CascadeType;
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.ManyToOne;
|
||||
import javax.persistence.NamedNativeQueries;
|
||||
import javax.persistence.NamedNativeQuery;
|
||||
import javax.persistence.NamedStoredProcedureQuery;
|
||||
import javax.persistence.ParameterMode;
|
||||
import javax.persistence.StoredProcedureParameter;
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.NamedNativeQueries;
|
||||
import jakarta.persistence.NamedNativeQuery;
|
||||
import jakarta.persistence.NamedStoredProcedureQuery;
|
||||
import jakarta.persistence.ParameterMode;
|
||||
import jakarta.persistence.StoredProcedureParameter;
|
||||
|
||||
import org.hibernate.envers.Audited;
|
||||
|
||||
|
|
|
@ -2,12 +2,12 @@ package com.baeldung.persistence.model;
|
|||
|
||||
import java.io.Serializable;
|
||||
|
||||
import javax.persistence.CascadeType;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.OneToOne;
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.OneToOne;
|
||||
|
||||
@Entity
|
||||
public class Parent implements Serializable {
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
package com.baeldung.persistence.model;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Person {
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
package com.baeldung.spring.data.jpa.query;
|
||||
|
||||
import javax.persistence.*;
|
||||
import jakarta.persistence.*;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
package com.baeldung.spring.data.jpa.query;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.persistence.criteria.*;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.PersistenceContext;
|
||||
import jakarta.persistence.criteria.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
|
|
@ -4,8 +4,8 @@ import static org.junit.Assert.assertEquals;
|
|||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.EntityManagerFactory;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
|
@ -30,15 +30,15 @@ import com.baeldung.spring.config.PersistenceTestConfig;
|
|||
@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
public class JPABarAuditIntegrationTest {
|
||||
|
||||
private static Logger logger = LoggerFactory.getLogger(JPABarAuditIntegrationTest.class);
|
||||
private static final Logger logger = LoggerFactory.getLogger(JPABarAuditIntegrationTest.class);
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpBeforeClass() throws Exception {
|
||||
public static void setUpBeforeClass() {
|
||||
logger.info("setUpBeforeClass()");
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void tearDownAfterClass() throws Exception {
|
||||
public static void tearDownAfterClass(){
|
||||
logger.info("tearDownAfterClass()");
|
||||
}
|
||||
|
||||
|
|
|
@ -3,8 +3,8 @@ package com.baeldung.persistence.audit;
|
|||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.EntityManagerFactory;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
|
@ -29,7 +29,7 @@ import com.baeldung.spring.config.PersistenceTestConfig;
|
|||
@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
public class SpringDataJPABarAuditIntegrationTest {
|
||||
|
||||
private static Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditIntegrationTest.class);
|
||||
private static final Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditIntegrationTest.class);
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpBeforeClass() throws Exception {
|
||||
|
@ -37,7 +37,7 @@ public class SpringDataJPABarAuditIntegrationTest {
|
|||
}
|
||||
|
||||
@AfterClass
|
||||
public static void tearDownAfterClass() throws Exception {
|
||||
public static void tearDownAfterClass(){
|
||||
logger.info("tearDownAfterClass()");
|
||||
}
|
||||
|
||||
|
|
|
@ -17,7 +17,7 @@ public class FooFixtures {
|
|||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FooFixtures.class);
|
||||
|
||||
private SessionFactory sessionFactory;
|
||||
private final SessionFactory sessionFactory;
|
||||
|
||||
public FooFixtures(final SessionFactory sessionFactory) {
|
||||
super();
|
||||
|
@ -28,8 +28,8 @@ public class FooFixtures {
|
|||
// API
|
||||
|
||||
public void createBars() {
|
||||
Session session = null;
|
||||
Transaction tx = null;
|
||||
Session session;
|
||||
Transaction tx;
|
||||
session = sessionFactory.openSession();
|
||||
tx = session.getTransaction();
|
||||
try {
|
||||
|
@ -39,13 +39,13 @@ public class FooFixtures {
|
|||
bar.setName("Bar_" + i);
|
||||
final Foo foo = new Foo("Foo_" + (i + 120));
|
||||
foo.setBar(bar);
|
||||
session.save(foo);
|
||||
session.persist(foo);
|
||||
final Foo foo2 = new Foo(null);
|
||||
if (i % 2 == 0) {
|
||||
foo2.setName("LuckyFoo" + (i + 120));
|
||||
}
|
||||
foo2.setBar(bar);
|
||||
session.save(foo2);
|
||||
session.persist(foo2);
|
||||
bar.getFooSet().add(foo);
|
||||
bar.getFooSet().add(foo2);
|
||||
session.merge(bar);
|
||||
|
@ -53,16 +53,12 @@ public class FooFixtures {
|
|||
tx.commit();
|
||||
session.flush();
|
||||
} catch (final HibernateException he) {
|
||||
if (tx != null) {
|
||||
tx.rollback();
|
||||
}
|
||||
tx.rollback();
|
||||
LOGGER.error("Not able to open session", he);
|
||||
} catch (final Exception e) {
|
||||
LOGGER.error(e.getLocalizedMessage(), e);
|
||||
} finally {
|
||||
if (session != null) {
|
||||
session.close();
|
||||
}
|
||||
session.close();
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -86,23 +82,18 @@ public class FooFixtures {
|
|||
try {
|
||||
tx.begin();
|
||||
for (final Foo foo : fooList) {
|
||||
|
||||
session.save(foo.getBar());
|
||||
session.save(foo);
|
||||
session.persist(foo.getBar());
|
||||
session.persist(foo);
|
||||
}
|
||||
tx.commit();
|
||||
session.flush();
|
||||
} catch (final HibernateException he) {
|
||||
if (tx != null) {
|
||||
tx.rollback();
|
||||
}
|
||||
tx.rollback();
|
||||
LOGGER.error("Not able to open session", he);
|
||||
} catch (final Exception e) {
|
||||
LOGGER.error(e.getLocalizedMessage(), e);
|
||||
} finally {
|
||||
if (session != null) {
|
||||
session.close();
|
||||
}
|
||||
session.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,19 +1,19 @@
|
|||
package com.baeldung.persistence.hibernate;
|
||||
|
||||
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.lessThan;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.hibernate.Criteria;
|
||||
import org.hibernate.Query;
|
||||
import org.hibernate.ScrollMode;
|
||||
import org.hibernate.ScrollableResults;
|
||||
import org.hibernate.Session;
|
||||
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.Before;
|
||||
import org.junit.Test;
|
||||
|
@ -28,6 +28,8 @@ import com.baeldung.persistence.service.IFooService;
|
|||
import com.baeldung.spring.config.PersistenceTestConfig;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
import jakarta.persistence.criteria.CriteriaQuery;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
public class FooPaginationPersistenceIntegrationTest {
|
||||
|
@ -40,8 +42,6 @@ public class FooPaginationPersistenceIntegrationTest {
|
|||
|
||||
private Session session;
|
||||
|
||||
// tests
|
||||
|
||||
@Before
|
||||
public final void before() {
|
||||
final int minimalNumberOfEntities = 25;
|
||||
|
@ -59,20 +59,17 @@ public class FooPaginationPersistenceIntegrationTest {
|
|||
session.close();
|
||||
}
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public final void whenContextIsBootstrapped_thenNoExceptions() {
|
||||
//
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public final void whenRetrievingPaginatedEntities_thenCorrectSize() {
|
||||
final int pageNumber = 1;
|
||||
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.setMaxResults(pageSize);
|
||||
final List<Foo> fooList = query.list();
|
||||
|
@ -80,19 +77,18 @@ public class FooPaginationPersistenceIntegrationTest {
|
|||
assertThat(fooList, hasSize(pageSize));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public final void whenRetrievingAllPages_thenCorrect() {
|
||||
int pageNumber = 1;
|
||||
final int pageSize = 10;
|
||||
|
||||
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 List<Foo> fooList = Lists.newArrayList();
|
||||
int totalEntities = 0;
|
||||
final Query query = session.createQuery("From Foo");
|
||||
final Query<Foo> query = session.createQuery("From Foo", Foo.class);
|
||||
while (totalEntities < countResult) {
|
||||
query.setFirstResult((pageNumber - 1) * pageSize);
|
||||
query.setMaxResults(pageSize);
|
||||
|
@ -102,17 +98,16 @@ public class FooPaginationPersistenceIntegrationTest {
|
|||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public final void whenRetrievingLastPage_thenCorrectSize() {
|
||||
final int pageSize = 10;
|
||||
|
||||
final String countQ = "Select count (f.id) from Foo f";
|
||||
final Query countQuery = session.createQuery(countQ);
|
||||
final Long countResults = (Long) countQuery.uniqueResult();
|
||||
final Query<Long> countQuery = session.createQuery(countQ, Long.class);
|
||||
final Long countResults = countQuery.uniqueResult();
|
||||
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.setMaxResults(pageSize);
|
||||
final List<Foo> lastPage = selectQuery.list();
|
||||
|
@ -126,9 +121,9 @@ public class FooPaginationPersistenceIntegrationTest {
|
|||
public final void givenUsingTheScrollableApi_whenRetrievingPaginatedData_thenCorrect() {
|
||||
final int pageSize = 10;
|
||||
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();
|
||||
// final int totalResults = resultScroll.getRowNumber() + 1;
|
||||
|
@ -138,7 +133,7 @@ public class FooPaginationPersistenceIntegrationTest {
|
|||
final List<Foo> fooPage = Lists.newArrayList();
|
||||
int i = 0;
|
||||
while (pageSize > i++) {
|
||||
fooPage.add((Foo) resultScroll.get(0));
|
||||
fooPage.add((Foo) resultScroll.get());
|
||||
if (!resultScroll.next()) {
|
||||
break;
|
||||
}
|
||||
|
@ -147,36 +142,42 @@ public class FooPaginationPersistenceIntegrationTest {
|
|||
assertThat(fooPage, hasSize(lessThan(10 + 1)));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public final void givenUsingTheCriteriaApi_whenRetrievingFirstPage_thenCorrect() {
|
||||
final int pageSize = 10;
|
||||
|
||||
final Criteria criteria = session.createCriteria(Foo.class);
|
||||
criteria.setFirstResult(0);
|
||||
criteria.setMaxResults(pageSize);
|
||||
final List<Foo> firstPage = criteria.list();
|
||||
CriteriaQuery<Foo> selectQuery = session.getCriteriaBuilder().createQuery(Foo.class);
|
||||
selectQuery.from(Foo.class);
|
||||
|
||||
SelectionQuery<Foo> query = session.createQuery(selectQuery);
|
||||
query.setFirstResult(0);
|
||||
query.setMaxResults(pageSize);
|
||||
final List<Foo> firstPage = query.list();
|
||||
|
||||
assertThat(firstPage, hasSize(pageSize));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public final void givenUsingTheCriteriaApi_whenRetrievingPaginatedData_thenCorrect() {
|
||||
final Criteria criteriaCount = session.createCriteria(Foo.class);
|
||||
criteriaCount.setProjection(Projections.rowCount());
|
||||
final Long count = (Long) criteriaCount.uniqueResult();
|
||||
|
||||
HibernateCriteriaBuilder qb = session.getCriteriaBuilder();
|
||||
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;
|
||||
final int pageSize = 10;
|
||||
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;
|
||||
while (totalEntities < count.intValue()) {
|
||||
criteria.setFirstResult((pageNumber - 1) * pageSize);
|
||||
criteria.setMaxResults(pageSize);
|
||||
fooList.addAll(criteria.list());
|
||||
query.setFirstResult((pageNumber - 1) * pageSize);
|
||||
query.setMaxResults(pageSize);
|
||||
fooList.addAll(query.list());
|
||||
totalEntities = fooList.size();
|
||||
pageNumber++;
|
||||
}
|
||||
|
|
|
@ -2,15 +2,17 @@ package com.baeldung.persistence.hibernate;
|
|||
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import org.hibernate.Criteria;
|
||||
import org.hibernate.NullPrecedence;
|
||||
import org.hibernate.Query;
|
||||
import org.hibernate.Session;
|
||||
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.Before;
|
||||
import org.junit.Test;
|
||||
|
@ -26,6 +28,8 @@ import com.baeldung.persistence.model.Bar;
|
|||
import com.baeldung.persistence.model.Foo;
|
||||
import com.baeldung.spring.config.PersistenceTestConfig;
|
||||
|
||||
import jakarta.persistence.criteria.CriteriaQuery;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
@SuppressWarnings("unchecked")
|
||||
|
@ -91,7 +95,7 @@ public class FooSortingPersistenceIntegrationTest {
|
|||
@Test
|
||||
public final void whenHQlSortingByOneAttribute_andOrderDirection_thenPrintSortedResults() {
|
||||
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();
|
||||
for (final Foo foo : fooList) {
|
||||
LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId());
|
||||
|
@ -101,7 +105,7 @@ public class FooSortingPersistenceIntegrationTest {
|
|||
@Test
|
||||
public final void whenHQlSortingByMultipleAttributes_thenSortedResults() {
|
||||
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();
|
||||
for (final Foo foo : fooList) {
|
||||
LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId());
|
||||
|
@ -111,7 +115,7 @@ public class FooSortingPersistenceIntegrationTest {
|
|||
@Test
|
||||
public final void whenHQlSortingByMultipleAttributes_andOrderDirection_thenPrintSortedResults() {
|
||||
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();
|
||||
for (final Foo foo : fooList) {
|
||||
LOGGER.debug("Name: {}, Id: {}", foo.getName(), foo.getId());
|
||||
|
@ -120,9 +124,12 @@ public class FooSortingPersistenceIntegrationTest {
|
|||
|
||||
@Test
|
||||
public final void whenHQLCriteriaSortingByOneAttr_thenPrintSortedResults() {
|
||||
final Criteria criteria = session.createCriteria(Foo.class, "FOO");
|
||||
criteria.addOrder(Order.asc("id"));
|
||||
final List<Foo> fooList = criteria.list();
|
||||
CriteriaQuery<Foo> selectQuery = session.getCriteriaBuilder().createQuery(Foo.class);
|
||||
selectQuery.from(Foo.class);
|
||||
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) {
|
||||
LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName());
|
||||
}
|
||||
|
@ -130,10 +137,16 @@ public class FooSortingPersistenceIntegrationTest {
|
|||
|
||||
@Test
|
||||
public final void whenHQLCriteriaSortingByMultipAttr_thenSortedResults() {
|
||||
final Criteria criteria = session.createCriteria(Foo.class, "FOO");
|
||||
criteria.addOrder(Order.asc("name"));
|
||||
criteria.addOrder(Order.asc("id"));
|
||||
final List<Foo> fooList = criteria.list();
|
||||
|
||||
CriteriaQuery<Foo> selectQuery = session.getCriteriaBuilder().createQuery(Foo.class);
|
||||
selectQuery.from(Foo.class);
|
||||
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) {
|
||||
LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName());
|
||||
}
|
||||
|
@ -141,9 +154,15 @@ public class FooSortingPersistenceIntegrationTest {
|
|||
|
||||
@Test
|
||||
public final void whenCriteriaSortingStringNullsLastAsc_thenNullsLast() {
|
||||
final Criteria criteria = session.createCriteria(Foo.class, "FOO");
|
||||
criteria.addOrder(Order.asc("name").nulls(NullPrecedence.LAST));
|
||||
final List<Foo> fooList = criteria.list();
|
||||
CriteriaQuery<Foo> selectQuery = session.getCriteriaBuilder().createQuery(Foo.class);
|
||||
selectQuery.from(Foo.class);
|
||||
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());
|
||||
for (final Foo foo : fooList) {
|
||||
LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName());
|
||||
|
@ -152,9 +171,15 @@ public class FooSortingPersistenceIntegrationTest {
|
|||
|
||||
@Test
|
||||
public final void whenCriteriaSortingStringNullsFirstDesc_thenNullsFirst() {
|
||||
final Criteria criteria = session.createCriteria(Foo.class, "FOO");
|
||||
criteria.addOrder(Order.desc("name").nulls(NullPrecedence.FIRST));
|
||||
final List<Foo> fooList = criteria.list();
|
||||
CriteriaQuery<Foo> selectQuery = session.getCriteriaBuilder().createQuery(Foo.class);
|
||||
selectQuery.from(Foo.class);
|
||||
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());
|
||||
for (final Foo foo : fooList) {
|
||||
LOGGER.debug("Id: {}, FirstName: {}", foo.getId(), foo.getName());
|
||||
|
@ -164,7 +189,7 @@ public class FooSortingPersistenceIntegrationTest {
|
|||
@Test
|
||||
public final void whenSortingBars_thenBarsWithSortedFoos() {
|
||||
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();
|
||||
for (final Bar bar : barList) {
|
||||
final Set<Foo> fooSet = bar.getFooSet();
|
||||
|
|
|
@ -5,14 +5,14 @@ import static org.junit.Assert.assertEquals;
|
|||
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.StoredProcedureQuery;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.EntityManagerFactory;
|
||||
import jakarta.persistence.StoredProcedureQuery;
|
||||
|
||||
import org.hibernate.Query;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.exception.SQLGrammarException;
|
||||
import org.hibernate.query.Query;
|
||||
import org.junit.After;
|
||||
import org.junit.Assume;
|
||||
import org.junit.Before;
|
||||
|
@ -59,22 +59,22 @@ public class FooStoredProceduresLiveTest {
|
|||
|
||||
private boolean getFoosByNameExists() {
|
||||
try {
|
||||
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
|
||||
Query<Foo> sqlQuery = session.createNativeQuery("CALL GetFoosByName()",Foo.class);
|
||||
sqlQuery.list();
|
||||
return true;
|
||||
} catch (SQLGrammarException e) {
|
||||
LOGGER.error("WARNING : GetFoosByName() Procedure is may be missing ", e);
|
||||
LOGGER.error("WARNING : GetFoosByName() Procedure may be missing ", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean getAllFoosExists() {
|
||||
try {
|
||||
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
|
||||
Query<Foo> sqlQuery = session.createNativeQuery("CALL GetAllFoos()",Foo.class);
|
||||
sqlQuery.list();
|
||||
return true;
|
||||
} catch (SQLGrammarException e) {
|
||||
LOGGER.error("WARNING : GetAllFoos() Procedure is may be missing ", e);
|
||||
LOGGER.error("WARNING : GetAllFoos() Procedure may be missing ", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
@ -90,9 +90,9 @@ public class FooStoredProceduresLiveTest {
|
|||
|
||||
fooService.create(new Foo(randomAlphabetic(6)));
|
||||
|
||||
// Stored procedure getAllFoos using createSQLQuery
|
||||
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
// Stored procedure getAllFoos using createQuery
|
||||
Query<Foo> sqlQuery = session.createNativeQuery("CALL GetAllFoos()", Foo.class);
|
||||
|
||||
List<Foo> allFoos = sqlQuery.list();
|
||||
for (Foo foo : allFoos) {
|
||||
LOGGER.info("getAllFoos() SQL Query result : {}", foo.getName());
|
||||
|
@ -100,8 +100,8 @@ public class FooStoredProceduresLiveTest {
|
|||
assertEquals(allFoos.size(), fooService.findAll().size());
|
||||
|
||||
// Stored procedure getAllFoos using a Named Query
|
||||
Query namedQuery = session.getNamedQuery("callGetAllFoos");
|
||||
@SuppressWarnings("unchecked")
|
||||
Query<Foo> namedQuery = session.createNamedQuery("callGetAllFoos", Foo.class);
|
||||
|
||||
List<Foo> allFoos2 = namedQuery.list();
|
||||
for (Foo foo : allFoos2) {
|
||||
LOGGER.info("getAllFoos() NamedQuery result : {}", foo.getName());
|
||||
|
@ -110,6 +110,7 @@ public class FooStoredProceduresLiveTest {
|
|||
|
||||
StoredProcedureQuery spQuery =
|
||||
entityManager.createNamedStoredProcedureQuery("GetAllFoos");
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Foo> allFoos3 = spQuery.getResultList();
|
||||
for (Foo foo : allFoos3) {
|
||||
LOGGER.info("getAllFoos() StoredProcedureQuery result : {}", foo.getName());
|
||||
|
@ -124,16 +125,16 @@ public class FooStoredProceduresLiveTest {
|
|||
fooService.create(new Foo("NewFooName"));
|
||||
|
||||
// Stored procedure getFoosByName using createSQLQuery()
|
||||
Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)").addEntity(Foo.class).setParameter("fooName", "NewFooName");
|
||||
@SuppressWarnings("unchecked")
|
||||
Query<Foo> sqlQuery = session.createNativeQuery("CALL GetFoosByName(:fooName)", Foo.class).setParameter("fooName", "NewFooName");
|
||||
|
||||
List<Foo> allFoosByName = sqlQuery.list();
|
||||
for (Foo foo : allFoosByName) {
|
||||
LOGGER.info("getFoosByName() using SQL Query : found => {}", foo.toString());
|
||||
}
|
||||
|
||||
// Stored procedure getFoosByName using getNamedQuery()
|
||||
Query namedQuery = session.getNamedQuery("callGetFoosByName").setParameter("fooName", "NewFooName");
|
||||
@SuppressWarnings("unchecked")
|
||||
Query<Foo> namedQuery = session.createQuery("callGetFoosByName", Foo.class).setParameter("fooName", "NewFooName");
|
||||
|
||||
List<Foo> allFoosByName2 = namedQuery.list();
|
||||
for (Foo foo : allFoosByName2) {
|
||||
LOGGER.info("getFoosByName() using Native Query : found => {}", foo.toString());
|
||||
|
@ -142,6 +143,7 @@ public class FooStoredProceduresLiveTest {
|
|||
StoredProcedureQuery spQuery = entityManager.
|
||||
createNamedStoredProcedureQuery("GetFoosByName")
|
||||
.setParameter("fooName", "NewFooName");
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Foo> allFoosByName3 = spQuery.getResultList();
|
||||
assertEquals(1, allFoosByName3.size());
|
||||
for (Foo foo : allFoosByName3) {
|
||||
|
|
Loading…
Reference in New Issue