BAEL-2809 Get all Data in a table with Hibernate (#5670)

* BAEL-2809 Get all Data in a table with Hibernate

* Delete transaction.log

* Update FindAll.java

* Update FindAllTest.java

* Update FindAll.java

* Update FindAllTest.java

* Rename FindAllTest.java to FindAllUnitTest.java
This commit is contained in:
enpy 2018-11-27 16:21:45 +01:00 committed by Emily Cheyne
parent 5ba5b60536
commit 71bca76bf8
2 changed files with 98 additions and 0 deletions

View File

@ -0,0 +1,35 @@
package com.baeldung.hibernate.findall;
import java.util.List;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.hibernate.Session;
import com.baeldung.hibernate.pojo.Student;
public class FindAll {
private Session session;
public FindAll(Session session) {
super();
this.session = session;
}
public List<Student> findAllWithJpql() {
return session.createQuery("SELECT a FROM Student a", Student.class).getResultList();
}
public List<Student> findAllWithCriteriaQuery() {
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Student> cq = cb.createQuery(Student.class);
Root<Student> rootEntry = cq.from(Student.class);
CriteriaQuery<Student> all = cq.select(rootEntry);
TypedQuery<Student> allQuery = session.createQuery(all);
return allQuery.getResultList();
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.hibernate.findall;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.hibernate.HibernateUtil;
import com.baeldung.hibernate.pojo.Student;
public class FindAllUnitTest {
private Session session;
private Transaction transaction;
private FindAll findAll;
@Before
public void setUp() throws IOException {
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
findAll = new FindAll(session);
session.createNativeQuery("delete from Student").executeUpdate();
Student student1 = new Student();
session.persist(student1);
Student student2 = new Student();
session.persist(student2);
Student student3 = new Student();
session.persist(student3);
transaction.commit();
transaction = session.beginTransaction();
}
@After
public void tearDown() {
transaction.rollback();
session.close();
}
@Test
public void givenCriteriaQuery_WhenFindAll_ThenGetAllPersons() {
List<Student> list = findAll.findAllWithCriteriaQuery();
assertEquals(3, list.size());
}
@Test
public void givenJpql_WhenFindAll_ThenGetAllPersons() {
List<Student> list = findAll.findAllWithJpql();
assertEquals(3, list.size());
}
}