Creating_and_Reading_Objects_with_Hibernate_Features_-Notes_lyst8673
Creating_and_Reading_Objects_with_Hibernate_Features_-Notes_lyst8673
Problems on Hibernate
Now that we understood the basics of Hibernate, let us try some scenario-based questions
to deepen our understanding of CRUD operations.
Scenario 1:
Fetch one row from the table
Consider the below table,
Student Table:
roll name Mail id
1 alex [email protected]
2 bob [email protected]
Program2.java
package com.tapacad.application;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.tapacad.model.Student;
public class Program2 {
// Create Transaction
Transaction transaction = session.beginTransaction();
// CRUD Operations
Student s = session.get(Student.class, 1);
System.out.println(s);
transaction.commit();
} finally {
// Closing Resources
session.close();
sessionFactory.close();
}
}
}
Output:
As we can see from the code, using session.get() we can fetch one row from the table.
Whenever we try to fetch the data which is not present in the database that time it will
return null.
Scenario 2:
Fetch all rows from the table
Consider the below table,
1 alex [email protected]
2 bob [email protected]
- To fetch all the data present in the table it is required to make use of Hibernate
Query Language (HQL) which is similar to SQL query language.
Logic:
String hql = "From Student"; //Here first we need to tell from
which class we are fetching the data
Query createQuery = session.createQuery(hql); //createQuery()
method generate query object
List students = createQuery.list(); //This will help you to
fetch all Student objects
Program3.java
package com.tap.app;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import com.tap.model.Student;
config.configure();
config.addAnnotatedClass(Student.class);
// Logics
String hql = "From Student";
Query createQuery = session.createQuery(hql);
List students = createQuery.list();
display(students);
transaction.commit();
Output:
As you can see from the above output, using hql query you can fetch all the data present
in the table and as overriding of toString() is done you are getting roll number, name,
email id.
Scenario 3:
Fetch all rows from the table where the marks of the student is greater than 90
or the name of the student starts with c
Consider the below table,
1 bob [email protected] 97
3 charli [email protected] 40
5 elton [email protected] 92
Logic:
String hql = "From Student s where s.marks > 90 or s.name LIKE
'c%' "; //Here query is written to fetch all the data whose
marks is greater than 90 or name starting with c
Query createQuery = session.createQuery(hql); // Here query
object is created
List students = createQuery.list(); // This will give list of
object who matches the criteria
Program4.java
package com.tap.app;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import com.tap.model.Student;
config.configure();
config.addAnnotatedClass(Student.class);
// Logics
String hql = "From Student s where s.marks > 90 or s.name LIKE 'c%' ";
Query createQuery = session.createQuery(hql);
List students = createQuery.list();
display(students);
transaction.commit();
Output:
As you can see from the above these are the students who have marks greater than 90
or name starts with c
Scenario 4:
1 bob [email protected] 97
3 charli [email protected] 40
5 elton [email protected] 92
Logic:
Student student = session.get(Student.class, 1); // Here
student object we are getting whose marks we want to update or
change
student.setMarks(25); // update the marks of the student object
using setter
Program5.java
package com.tap.app;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import com.tap.model.Student;
config.configure();
config.addAnnotatedClass(Student.class);
// Logics
Student student = session.get(Student.class, 1);
student.setMarks(25);
transaction.commit();
Output:
1 bob [email protected] 25
3 charli [email protected] 40
5 elton [email protected] 92
If you can see from the above table, bob marks have been updated.
One more way of updating marks of the student is by making use of update()
Program6.java
package com.tap.app;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import com.tap.model.Student;
config.configure();
config.addAnnotatedClass(Student.class);
// Logics
// Student student = session.get(Student.class, 1);
// student.setMarks(25);
transaction.commit();
The above code gives an exception because when you are updating the value there should
be a match in the primary key of the table.
Scenario 5:
Given the student object, update the data of the student if the student exists in the table. If
student is new data insert the student into the table
Logic:
Student student = new Student(6, "zakir", "[email protected]",
75); // Create a object that you want to insert or update in
database
Program7.java
package com.tap.app;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.tap.model.Student;
config.configure();
config.addAnnotatedClass(Student.class);
// Logics
transaction.commit();
Output:
Data base
1 bob [email protected] 25
3 charli [email protected] 40
5 elton [email protected] 92
6 zakir [email protected] 75
If you observe the table zakir data was not there so using saveOrUpdate() you can
update the data if the user exists else insert new data if the user doesn’t exist
Now we will try to update the marks of the elton by making use of saveOrUpdate()
Program8.java
package com.tap.app;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.tap.model.Student;
config.configure();
config.addAnnotatedClass(Student.class);
// Logics
// Student student = session.get(Student.class, 1);
// student.setMarks(25);
transaction.commit();
}
private static void display(List students) {
for (Object student : students) {
System.out.println(student);
}
Data base
1 bob [email protected] 25
3 charli [email protected] 40
5 elton [email protected] 75
6 zakir [email protected] 75
Now, if you observe the above table elton marks has been updated with 75
Scenario 6:
Update the marks of all the students to 50 whose marks is less than 50
1 bob [email protected] 25
3 charli [email protected] 40
5 elton [email protected] 75
6 zakir [email protected] 75
program9.java
package com.tap.app;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import com.tap.model.Student;
public class Program1 {
public static void main(String[] args) {
Configuration config = new Configuration();
config.configure();
config.addAnnotatedClass(Student.class);
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
// Logics
String hql = "UPDATE Student s SET s.marks = 50 WHERE s.marks < 50";
Query query = session.createQuery(hql);
int i = query.executeUpdate();
System.out.println(i);
transaction.commit();
}
}
}
Database
1 bob [email protected] 50
3 charli [email protected] 50
5 elton [email protected] 75
6 zakir [email protected] 75
Now if you can see from the above table bob and charli marks were less than 50 now it is
updated with the value 50. In the above program executeUpdate() will return number of
rows it has updated
Scenario 7:
Now let’s see how to delete single row from the table
Logic:
Consider the table below, here we will delete zakir data from the table
1 bob [email protected] 50
3 charli [email protected] 50
5 elton [email protected] 75
6 zakir [email protected] 75
Program10.java
package com.tap.app;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import com.tap.model.Student;
config.configure();
config.addAnnotatedClass(Student.class);
// Logics
Student student = session.get(Student.class, 6);
session.delete(student);
transaction.commit();
Data base:
1 bob [email protected] 50
3 charli [email protected] 50
5 elton [email protected] 75
You can clearly see from the above table using delete() now zakir data with primary key
6 is been deleted from the database
Scenario 8:
Delete multiple row from the table where marks of the student is 50
1 bob [email protected] 50
3 charli [email protected] 50
5 elton [email protected] 75
Program11.java
package com.tap.app;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import com.tap.model.Student;
config.configure();
config.addAnnotatedClass(Student.class);
// Logics
String hql = "DELETE FROM Student s WHERE s.marks = 50";
Query query = session.createQuery(hql);
int i = query.executeUpdate();
System.out.println(i);
transaction.commit();
Database:
5 elton [email protected] 75
From the above table you can clearly see the row with marks equal to 50 is been deleted