Wednesday, November 18, 2015

Hibernate Hello world Program

Hibernate Hello world Program


Mates, here is the first program in hibernate like saving an object into the database (don’t think we are inserting a record into the database :-) that is the case in JDBC, in hibernate we are just saving an object into database, means inserting only) hope you got my contention,  as of now am giving this as normal console based java application, actually it’s bit tedious to set the class path every time for all the jar files but you must know this too.
From the next example i will give all the applications in the Eclipse
As i told you earlier,  these are the files we require to shape an hibernate program..
  • Product.java (My POJO class)
  • Product.hbm.xml  (Xml mapping file )
  • hibernate.cfg.xml  (Xml configuration file)
  • ClientForSave.java (java file to write our hibernate logic)

Product.java:

Product.hbm.xml:

In this mapping file, my Product class is linked with PRODUCTS table in the database, and next is the id element, means in the database table what column we need to take as primary key column, that property name we need to give here, actually i have been given my property name productId which will mapped with pid column in the table.
And proName is mapped with pname column of the PRODUCTS table, see i have not specified any column for the property price, this means that, our property name in the pojo class and the column name in the table both are same.
Remember: the first 3 lines is the DTD for the mapping file, as a programmer no need to remember but we need to be very careful while you are copying this DTD, program may not  be executed if you write DTD wrong, actually we have separate DTD’s for Mapping xml and Configuration xml files.

hibernate.cfg.xml:


In this configuration file i have been given my Oracle database connection properties, if you are using MySql then just specify your database related details actually its depends on you.

ClientForSave.java

Now compile all .java files and run ClientForSave.java and check the output

Output Eclipse

In The Database

Note:

  • Make sure all .class, .java, .xml files are exist in the same folder
  • Before you compile and run this application, ensure you set the class path for all 12 jars files, this is tedious like what i told you earlier, we can avoid this process from the next example with Eclipse, a real time tool ;)
  • except select operation, all other operations must be in the Transaction Scope

No comments:

Easy Way to Handle Android Notifications

Android Notifications Android Toast class provides a handy way to show users alerts but problem is that these alerts are not persist...