Hibernate Notes For Beginners Dinesh Sripathi - CodingWiz
Hibernate Notes For Beginners Dinesh Sripathi - CodingWiz
HIBERNATE
scalability, and maintainability in Java
applications.
ORM :
It used to link the java object with the database.
It is issue with the JDBC is that it will stick with the certain sql statements. Hence if we change the database
then we have to change the queries as well.
Hibernate Framework :
It is used to connect the database with the java.
How to create a project :
1. Here we create the maven project.
2. Then you have to give the group id and artifact id
a. GroupId : This is where we give the root folder
b. ArtifactId : This is where we have to give our project name.
3. In maven project we will have the pom.xml and it will contain all the dependencies.
4. To connect the Database we need the jar file. Here we just have to use the dependency code from the
maven repository.
5. To get that goto browser and type maven repository.
6. Search for the database connector and copy the maven dependencies and paste them in pom.xml.
a. We have to paste them inside the tag dependency.
Syntax :
<dependencies>
<dependency>
Paste the copied code
</dependency>
</dependencies>
Example :
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.3.0</version>
</dependency>
7. Also add the hibernate dependencies. Go to maven repo and search for hiberntate and paste the
dependency in pom file.
Example :
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.5.0.CR2</version>
</dependency>
8. If you are not able to see any maven dependencies then we have to follow the below steps.
a. Right click on the project
b. Select maven > right click
c. Select update maven
d. Update the maven project it will add the dependencies.
NOTE : If you are not able to see the hibernate option goto market place and search for hibernate tools. Install
jboss tool > select hibernate.
iv. Once it is done. Create the object for the sessionFactory which can get from
buildSessionFactory();
Syntax :
SessionFactory SFObject = configObject.buildSessionFactory();
Example :
SessionFactory sessionFactory = config.buildSessionFactory();
v. Then we have to open the session using the openSession method.
Syntax :
Session sessionObject = SFObject.openSession();
Example :
Session s = sessionFactory.openSession();
d. While creating the config file we have to pass the driver class, connection url, username and
password.
i. In order to insert the data 1st we have to register the class as entity (table) to the main
class to save the data.
1. To make a class as entity we use annotation.
Syntax :
@Entity
Example :
@Entity
public class Emp
2. Also register this class in the main java class where you are configuring it. With
the help of addAnnotatedClass after configure( ).
Syntax :
configObject.addAnnotatedClass(“className.class”);
Example :
conf.addAnnotatedClass(Emp.class);
NOTE : In hibernate we must declare at least one column as primary key to do that we have to use the @Id
annotation.
e. Before saving the data we have to get the transaction to save data into database.
Syntax :
Session.beginTransaction();
Example :
session.beginTransaction();
f. We use the session.save(object) to save in database.
Syntax :
sessionObject.save(EntityClassObject);
Example :
session.save(e1);
g. Apart from save session will also have delete, update methods to update the data or to delete it.
h. In database we perform the all the operations as transaction. Hence we have to commit the
operations to save data/ info in database.
Syntax :
configObject.getTransaction().commit();
Example :
session.getTransaction().commit();
Example :
package com.teks;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
session.beginTransaction();
Emp e1 = new Emp(1, "Tony",1000.00);
session.save(e1);
session.getTransaction().commit();
System.out.println("Saved...");
}
NOTE: To show the sql query we use the property name = “hibernate.show_sql” and set it to true in file
hibernate.cfg.xml.
Syntax :
<property name = “hibernate.show_sql”>true</property>
NOTE : The table name and the entity class must have the same name. If you want to use a different name then
we use the annotation called as Table and will provide the name there.
Syntax :
@Entity
@Table(name = “tableName”)
Public class className
Note : If the column names are different then we use the annotation called column to map it to the main column.
Syntax :
@Id
@column( name = “column name” )
Session Object :
It is a object which will provides us the helper methods. It generated from sessionFactory.
To generate the sessionFactory we have to do the configuration.
It doesn’t matter whether you are mentioning the hibernate.cfg.xml file in configuration as the hibernate
by default will look for it.
To create/ insert into table :
o We use the session.save(object) to save in database.
Syntax :
sessionObject.save(EntityClassObject);
Example :
session.save(e1);
session.getTransaction().commit();
System.out.println("Data Updated....");
NOTE: Here the data will update automatically even if you are not updating the data and run the code then the
hibernate will follow auto-dirty checking concept.
Auto-Dirty Checking :
Hibernate will check the persistent staged objects whether they are changed or not. If the object value
changed by the end of the closing session then it will update the value into the database as well.
1. Transient State :
a. The objects which are not associated with the objects are called as transient state.
b. You can say these are using before the session.
2. Persistent state :
a. The objects which are associated are called as persistent state.
3. Detached State :
a. If the object is no longer managing by the persistent state then it will fall under detached
state.
NOTE : We can use the contains object to check if the object is associated with the session or not. It will return
the Boolean values.
Syntax :
sessionObject.contains( object );
Options :
1. Update : used to update the data into database automatically by matching the enity. It will
create new columns and constraints if they didn’t exists. It will not drop or modify the table.
Example :
<property name = "hibernate.hbm2ddl.auto">update</property>
2. Create : Used to create database schemas from scratch based on entity mapping. It will drop
existing schema objects and recreate them if needed.
Example :
<property name = "hibernate.hbm2ddl.auto">create</property>
NOTE : Before running the main method drop the table
Output :
3. Create-drop : It is similar to create but it will also drop table if the sessionFactory is closed.
Example :
<property name = "hibernate.hbm2ddl.auto">create-drop</property>
Embeddable Object :
Here we can use the object as a column for the table. To do that we have use the annotation called as
Embeddable to the subclass.
Example for Entity :
@Entity
public class Trail {
@Id
private int id;
private Test t;
private double salary;
Hibernate Relations :
Here we are going to have the relations between tables, The types of the relations are
1. One to One
2. One to Many
3. Many to One
4. Many to Many
1. Using the OnetoOne annotation :
a. Imagine we are having two tables and when you want to form a relation then we have to use the
annotations for One to One we have to use @OnetoOne as it will create a foreign key
automatically for the table.
Example for Table 1 :
@Entity
@Table(name = "customer")
public class Customers {
@Id
@Column(name = "cust_id")
private int id;
private String name;
@OneToOne
@JoinColumn(name = "order_id")
private Orders order;
Example for Table 2 :
@Entity
@Table(name = "orders")
public class Orders {
@Id
@Column(name = "order_id")
private int id;
private String name;
Example for Main App :
Configuration config = new Configuration();
config.configure();
config.addAnnotatedClass(Customers.class);
config.addAnnotatedClass(Orders.class);
Session session = config.buildSessionFactory().openSession();
session.beginTransaction();
Orders o = new Orders(101,"iPhone");
Customers c = new Customers(1, "Ravi");
c.setOrder(o);
session.persist(o);
session.persist(c);
session.getTransaction().commit();
session.close();
2. Using one to many :
a. Here when we are trying to update or use the table then we have to use the one to many relation.
b. It will create a mapping table.
c. Also here the tables will get confused as we have to mention the table who will map create the
mapping table. To do that we have to use the property called as mappedBy
Syntax :
mappedBy = “EntityClassName”
Customer Table Example ;
@Entity
@Table(name = "customer")
public class Customers {
@Id
@Column(name = "cust_id")
private int cust_id;
private String name;
@OneToMany(mappedBy = "customer")
private List<Orders> order = new ArrayList<Orders>();
3. ManyToMany :
a. Here we will use to represent the many to many relation between tables.
Syntax :
@ManyToMany
Collection
Example for the CustomersTable :
@Entity
@Table(name = "customer")
public class Customers {
@Id
@Column(name = "cust_id")
private int cust_id;
private String name;
@ManyToMany(mappedBy = "customer")
private List<Orders> order = new ArrayList<Orders>();
o.getCustomer().add(c);
session.save(c);
session.save(o);
session.getTransaction().commit();
session.close();
createQuery :
It will return a query object after running the query.
Syntax :
sessionObject.createQuery(“ hql query here”);
Example :
Session.createQuery(“ SELECT E from Emp_details E ”);
Instead of declaring all the values we can use the entity name like as shown below :
Syntax :
sessionObject.createObject( “From TableName” );
Example :
String hql = "from Emp_details";
Query q = session.createQuery(hql);
if(e != null) {
for(Object e1 : e) {
System.out.println(e1);
}
}
Imagine where we are trying to get the set of data instead of returning a single object it will return a collection
of objects. Then we have to store them inside a list.
Example :
Query q = session.createQuery("select name, salary from EmpDetails E Where name = 'Mini' or salary >
3000");
for(Object[] obj : e) {
System.out.println(obj[0] + " " + obj[1]);
}
List l = q.list();
System.out.println(l);
To provide the data dynamically we can use the colon or question mark before the variable.
Syntax :
Where colName = :variable;
Example :
Query q = session.createQuery("select salary from EmpDetails E Where name = :check");
q.setParameter("check", "Maxi");
List<Double[]> l = q.list();
System.out.println(l);
NOTE : Before doing that we have to set the parameter for the variable to do that we have to use the method in
query.
Syntax :
queryObject.setParameter( key, value );
But it will return us an object as we don’t want the object instead of that we need the entity object. To get the
entity object we use the addEntity( ) method.
Syntax :
sqlObject.addEntity( EntityClass.class );
Example :
NativeQuery sql = session.createNativeQuery("select * from emp_details where salary = 2000");
sql.addEntity(EmpDetails.class);
for(EmpDetails e : emp) {
System.out.println(e);
}
JPA :
JPA Means Java Persistence API. It is a specification which will help us to change from one ORM to
another ORM. Hence we need to use the ORM tools to use the JPA.
If we need to fetch data from the database we use the find( ) method. It will accept us EntityName.class and the
id. This find method is actually belongs to interface EntityManager.
Entity Manager :
It is the main control center for managing your entities and interacting with the persistence context.
Entity Manager object will be provided by the EntityManagerFactory.
a. Using SessionObject :
Here we use the session object to create the entityManagerFactory( ).
Syntax :
EntityManagerFactory emf = session.getEntityManagerFactory();
EntityManager em = emf.createEntityManager();
Example :
Session session = config.buildSessionFactory().openSession();
session.beginTransaction();
EntityManagerFactory emf = session.getEntityManagerFactory();
EntityManager em = emf.createEntityManager();
System.out.println(em.find(EmpDetails.class, 3));
<persistence-unit name="jpa">
<properties>
<property name="jakarta.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
<property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/trail" />
<property name="jakarta.persistence.jdbc.user" value="root" />
<property name="jakarta.persistence.jdbc.password" value="0000" />
<!-- <property name="jakarta.persistence.schema-generation.database.action" value="create" /> -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
</properties>
</persistence-unit>
</persistence>