There also exists some more advanced query methods, like native query and criteria query, which
we will discuss in the next chapter when we talk about JPA.
To test the method, add the code snippet in Listing 9-21 into the SpringHibernateSample class.
Listing 9-21. Testing the findById Method
Contact contact;
// Find contact by ID
contact = contactDao.findById(1l);
System.out.println("");
System.out.println("Contact with id 1:" + contact);
System.out.println("");
Running the program will produce the following output (other output was omitted):
Contact with id 1:Contact - Id: 1, First name: Clarence, Last name: Ho, Birthday: 1980-07-30
Inserting Data
Inserting data in Hibernate is very simple. One other fancy thing is retrieving the database-generated
primary key. In the previous chapter on JDBC, we needed to explicitly declare that we wanted to retrieve
the generated key, pass in the KeyHolder, and get the key back from it after executing the insert
statement. With Hibernate, all those actions are not required. Hibernate will cleverly retrieve the
generated key and populate the domain object after insert. Listing 9-22 shows the implementation of the
save() method.
Listing 9-22. Implementing the save Method
package com.apress.prospring3.ch9.dao.hibernate;
// Import statements omitted
@Repository("contactDao")
@Transactional
public class ContactDaoImpl implements ContactDao {
// Other code omitted
public Contact save(Contact contact) {
sessionFactory.getCurrentSession().saveOrUpdate(contact);
log.info("Contact saved with id: " + contact.getId());
return contact;
}
}
We just need to invoke the Session.saveOrUpdate() method, which can be used for both insert and
update operations. We also log the ID of the saved contact object that will be populated by Hibernate
after the object is persisted. Let's test the insert operation. Listing 9-23 shows the code snippet for
inserting a new contact record. Add the code snippet into the SpringHibernateSample class.
Listing 9-23. Testing Insert Operation
// Add new contact
contact = new Contact();
contact.setFirstName("Michael");
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home