public Contact findById(Long id);
// Insert or update a contact
public Contact save(Contact contact);
// Delete a contact
public void delete(Contact contact);
}
The interface is very simple; it has just three finder methods, one save method, and one delete
method. The save() method will perform both the insert and update operations.
For the implementation class, the com.apress.prospring3.ch9.dao.hibernate.ContactDaoImpl class,
we begin with creating the class with an empty implementation of all the methods in the ContactDao
interface. In STS, it's very easy to do it. For details, please see the section "Setting UP JDBC DAO Using
Annotations" in Chapter 8.
Query Data Using Hibernate Query Language
Hibernate, together with other ORM tools such as JDO and JPA, is engineered around the object model.
So, after the mappings are defined, we don't need to construct SQL to interact with the database.
Instead, for Hibernate, we use the Hibernate Query Language (HQL) to define our queries. When
interacting with the database, Hibernate will translate the queries into SQL statements on our behalf.
When coding HQL queries, the syntax is quite like SQL. However, you need to think on the object
side rather than data side. We will go through several examples in the following sections.
Simple Query with Lazy Fetching
Let's begin with the findAll() method, which simply retrieves all the contacts from the database. Listing
9-14 shows the code snippet.
Listing 9-14. Implementing the findAll Method
package com.apress.prospring3.ch9.dao.hibernate;
// Import statements omitted
@Repository("contactDao")
@Transactional
public class ContactDaoImpl implements ContactDao {
// Other code omitted
@Transactional(readOnly=true)
public List<Contact> findAll() {
return sessionFactory.getCurrentSession().
createQuery("from Contact c").list();
}
}
As shown in Listing 9-14, the method SessionFactory.getCurrentSession() gets hold of Hibernate's
Session interface. Then, the Session.createQuery() method is called, passing in the HQL statement. The
statement from Contact c simply retrieves all contacts from the database. An alternative syntax for the
statement is select c from Contact c. The @Transactional(readOnly=true), which means we want
the transaction to be set as read-only. Setting that attribute for finder methods will result in better
performance.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home