Search⌘ K

Develop the Data Access Tier

Explore how to develop the data access tier in Java applications using Hibernate. Learn to implement create, read, update, and delete operations through test-driven examples, mastering the use of Session.save, Session.get, Session.delete, and Session.merge methods to manage database interactions effectively.

“Find all records” operation

We will begin with the test case for the “find all records” operation.

Java
@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration( locations = { "classpath:context.xml" } )
@TransactionConfiguration( defaultRollback = true )
@Transactional
public class EmployeeDaoImplTest {
@Autowired
private EmployeeDao dao ;
@Test
public void testGetAll() {
Assert.assertEquals(0L, dao.getAll().size());
}
}

We will then see how to write the corresponding data access operation of the above test.

Java
@Repository
@Transactional
public class EmployeeDaoImpl implements EmployeeDao {
@Autowired
private SessionFactory sessionFactory ;
@SuppressWarnings("unchecked")
@Override
public List<Employee> getAll() {
return sessionFactory.getCurrentSession().createQuery("select employee from Employee employee order by employee.id desc").list();
}
}

Insert operation

Let’s ...