Saturday, March 2, 2013

Hibernate Course: Section 3: V11- V16 Hibernate Basics

V11: Setup the project
you should add the following maven dependencies

and we should add file in src/main/resources

it is good practice to put your entities in specific packages like

Video 12: Simple Entity Mapping
in the previous image we introduced the following annotations

1- @Entity: to define an entity
2- @Table: to set the table
3-@Id: to set the primary key
4- @GeneratedValue: to set the way you generate a new id
5- @Column: to set the column

Note: it is a good practice to always set the table and column names, even though Hibernate can do some magic to link them,

Video 13: prepare you application with
in this lesson we will see how we can use to setup our application

1- add to the resources file:

2- now we will define a HibernateUtils class, in this class we will write the code responsible for creating a sessionFactory and other stuff

as you can see we are using singleton pattern, only one sessionFactory will be created

we define a Configuration object, which will automatically read the file,
as you can see we have to add the Entity classes to configurations

if you have other classes you should add all of them

then we call buildSessionFactory()

Video 15: setup the project with hibernate.cfg.xml
hibernate.cfg.xml is the preffered way to write configurations, it has more options to add than

as you can see we added the connection information,
show_sql: will print the executed sql statement to the output

and the most important thing is mapping, here we define the Entity classes, we cannot do that in, as you can see from the previous video you should add them by using configuration.addAnnotatedClass(User.class) if you are using

now the HibernateUtil will look like this

as you can see no more configuration.addAnnotatedClass()

Video 16: Calling Persistence method
as you can see, we get a session factory and we open a session
then we begin a transaction
then we save
commit the transaction
then close the session.

Note: remember to commit the transaction before you close the session.

No comments:

Post a Comment