|
In the previous section,we tested the basic functionality of our hibernate application. With few lines of code,we were able to perform the basic operations like insert,update and delete on the database table,and add few children without writing a single SQL query. In enterprise applications,an efficient search mechanism is highly needed. Hibernate provides a set of different techniques to search a persisted object. Let us see a simple mechanism to find an Object by primary key without using a query.
Add the following method in UserManager class.
public User getUser(long userId)
{
User user = (User)session.get(User.class, new Long(userId));
return user;
}
This is the whole logic of finding a user by primary key. Let's test this code by adding the following method in TestClient.
public void testFindByPk(UserManager manager)
{
User user = manager.getUser(1);//Find the user with id=1
if(user == null) {
System.out.println("No user found with ID=1");
}else {
System.out.println("User found with ID=" user.getUserId() "\n"
"\tName=" user.getLastName() "\n"
"\tEmail=" user.getEmail()
"");
java.util.Iterator numbers = user.getPhoneNumbers().iterator();
while(numbers.hasNext()) {
PhoneNumber ph = (PhoneNumber)numbers.next();
System.out.println("\t\tNumber Type:" ph.getNumberType() "\n"
"\t\tPhone Number:" ph.getPhone());
}
}
}
Add the call to this method in main. To do this,add the following line in main.
client.testFindByPk(manager);
Replace the user id 1 by some reasonable user id that exists in the database and there are few phone numbers added against that user id. You will see the following output.
User found with ID=1
Name=Elison
Email=john@visualbuilder.com
Number Type:Office
Phone Number:934757
Number Type:Home
Phone Number:934757
|