Writing Model Class and Saving Object

Steps required for saving a Model  without hibernate

  1. JDBC Database configuration
  2. The Model object
  3. service method to create teh model object
  4. Database design
  5. DAO method to save the object using sql queries.

When we are using hibernate lot of these are not required and it also becomes very easy so lets see it.

The Hibernate way

  1. JDBC databse configuration – hibernate configuration
  2. The Model Object-Annotations
  3. Service method to create the model object use the hibernate api
  4. Database design –not needed
  5. DAO method to save the object using sql queries–Not needed.

Now lets start coding our first application

After creating Java project and Adding the hibernate user defined library to it,the first we require is a hibernate.cfg.xml file.

Next we need is to create our Model class.In our example we are creating UserDetails with two attributes.

Annotation used are

@Entity –> Tells that this is a model class

@Id —> For Primary key

Next we need some class to instantiate the Userdetails object  so we will create HibernateTest

Here Session factory is only one object per application.It creates how many session you want in your application.

Now when we run the HibernateTest,hibernate will create a table with the name of the Entity class i.e Userdetails and coloumn with the attributes added in the class(id and name)

Output :

Hibernate: insert into UserDetails (name, userId) values (?, ?)


   

Share :Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Comments are closed