Now, we have reached a point from where we start the actual transactional operations, such as insert, delete, update, and so on.
In this recipe, we will look at how to save an object to the database.
The equivalent SQL query is as follows:
INSERT INTO department (deptName) VALUES ('department name');
INSERT INTO employee (firstName, salary, department) VALUES ('first name', salary value, department id);
Let's look at how to save an object to the database:
SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session session = sessionFactory.openSession(); // begin a transaction session.getTransaction().begin(); //creating a department object Department department = new Department(); department.setDeptName("developement"); // save department object session.save(department); System.out.println("Department saved, id: " + department.getId()); //creating an employee object Employee employee = new Employee(); employee.setFirstName("yogesh"); employee.setSalary(50000); // set department of employee employee.setDepartment(department); // save employee object session.save(employee); System.out.println("Employee saved, id: " + employee.getId()); // commit transaction session.getTransaction().commit(); session.close(); HibernateUtil.shutdown();
The output of the preceding code would be as follows:
Hibernate: insert into Department (deptName) values (?) Department saved, id: 1 Hibernate: insert into employee (department, firstName, salary) values (?, ?, ?) Employee saved, id: 1
In the output, hibernate shows all the queries in the values(…)
clause with the question mark (?
) sign. As hibernate used PreparedStatement
to save the record, it shows queries such as this one. If we want to see all the parameters set by hibernate, we have to configure a logging framework in our application. Log4j
is a widely used, easy to configure, and easy to use framework.
To configure Log4j
, we need some JAR files, which are easily available on the official site of Log4j
, http://logging.apache.org/log4j.
The Maven dependency for Log4j
is as follows:
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
Also, you need to create a file with the name log4j.properties
in your classpath. The minimal content of file should be as follows:
Source file: Log4j.properties
# Root logger option log4j.rootLogger=INFO, stdout # Direct log messages to stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout # Log JDBC bind parameter runtime arguments log4j.logger.org.hibernate.type=trace
If log4j
is configured, the output of the preceding code will be displayed as follows:
Hibernate: insert into Department (deptName) values (?) binding parameter [1] as [VARCHAR] - [developement] Department saved, id: 1 Hibernate: insert into Employee (department, firstName, salary) values (?, ?, ?) binding parameter [1] as [BIGINT] - [1] binding parameter [2] as [VARCHAR] - [yogesh] binding parameter [3] as [INTEGER] - [50000] Employee saved, id: 1
In the output, you can see the logs that show all the binding parameters in sequence.
Here, we created a department object and saved it using a Session
. Hibernate saved the record with id
equal to 1
; even though it is not provided by us via code, once we print the value of id
field, it shows up as 1
. Actually, the id
field is annotated with the @GeneratedValue
annotation, which acts as an autoincrement
column, and the database returns a saved object back to hibernate; so, we get id
with the value 1
here.
Perform the following steps to save the records:
SessionFactory
.SessionFactory
.In the preceding example, we saved the department first and then the employee. But this is just a sample case; in a working scenario, we cannot save the department every time. As we have a many-to-one relationship between department and employee, multiple employees can refer to a single department. So, we can use an already saved object, as shown in the following code:
SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session session = sessionFactory.openSession(); // begin a transaction session.getTransaction().begin(); //creating department object Department department = new Department(); department.setId(1l); //creating an employee object Employee employee = new Employee(); employee.setFirstName("aarush"); employee.setSalary(35000); // set department of employee employee.setDepartment(department); // save employee object session.save(employee); System.out.println("Employee saved, id: " + employee.getId()); // commit transaction session.getTransaction().commit(); session.close(); HibernateUtil.shutdown();
The output of the preceding code will be as follows:
Hibernate: insert into employee (department, firstName, salary) values (?, ?, ?) Employee saved, id: 2
Here, we create the department object and set the value to 1
in the id
field. Now, while saving an employee, hibernate sets the reference with the department having id=1
.