Java Hibernate Tutorial
Create table from Class Schema Change Insert record (object) Review
Java Persistance
When we write Java code, we create objects, and those objects
have properties. Here's a simple piece of code. Just by looking at it,
I think you can tell what the User's name and password are:
User user = new User(); //an object named user is created
user.setName("Cameron"); //name is initialized to Cameron
user.setPassword("n0tte11ing");//password is initialized to n0tte11ing
I think even the uninitiated Java programmer would recognize
that we have just created a user named Cameron with a
password of n0tte11ing. We see this type of object
creation and property initialization in Java programs all the time.
But the problem Java developers always have is figuring out how to
take the data associated with the object and save it to the database.
Hibernate makes the persistence of your Java objects,
aka Java Persistence, easy.
Just how easy is it to persist Java
objects with Hibernate?
With a magical and mystical object known as the Hibernate
Session, persisting the state of your Java objects is easy. Look how
readable and understandable the following code is:
User user = new User(); //an object named user is created
user.setName("Cameron"); //name is initialized to Cameron
user.setPassword("n0tte11ing");//password is initialized to n0tte11ing
Session hibernateSession = HibernateUtil.getSession();
//get the magical Hibernate session
hibernateSession.save(user); //save the user to the database!
The line of code hibernateSession.save(user); saves the
state of the user instance to the database. Of course, there's a
little bit of plumbing code that needs to go in there to make the
whole hibernate framework work; But setting up that plumbing code
really isn't that bad. Overall, Hibernate is real easy to use, fairly
easy to set up, and probably the easiest way to manage the persistent
state of you domain model objects.
|