Hibernate is an ORM (Object Relational Mapping) tool which is primarily used in the data layer.
Object Relational Mappings Problems
There are several problems can occur when you are trying to save objects in the database from the scratch without using Hibernate.
- Mapping member variables to columns
- Mapping relationships
- Handling data types
- Managing changes to an object
Set Up the Development Environment
Following steps are briefly pointed out how to set up Hibernate on your local machine.
- Download the hibernate jar files
- Create a project in Eclipse
- Right click on the project name and go to properties
- Navigate to libraries tab
- Add library and import jar files (lib-> JPA/required)
- Add Postgres JDBC driver as jar file
Configurations
After you set up the Hibernate you have to create hiberante.cfg.xml file and do some configurations like setup database details, entity class, etc.
- Dialect: Define what kind of language should use to talk to database
Annotations
You have to use several annotations in your class files to indicate several functionalities, then Hibernate can easily identify them.
@Entity: Indicate to treat the defined class as an entity name : define the class name @Id: Indicate to treat the defined field as primary key @Column: Indicate to treat the defined field as column name: define the column name - @Table: Indicate to treat the defined thing as table (doesn't change the entity name)
- name: define the table name
- @Transient: ignore the defined field as database field
- @Temporal: configure date and time functionalities
Use Hibernate API
We use Hibernate API functions to save the model object in the database. Following points describe the steps to save the model.
- Create a session factory (one time)
- Create a session using created session factory
- Save the model object in the database using created session
There are several API in-built functionalities we can use to save object using Hibernate.
- configure: take the configuration file and read it
- buildSessionFactory : return session factory
- openSession: create a new session
- beginTransaction: Indicate to start the work of session
Comments
Post a Comment