Saving an object to the database

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:

  • Department: INSERT INTO department (deptName) VALUES ('department name');
  • Employee: INSERT INTO employee (firstName, salary, department) VALUES ('first name', salary value, department id);

How to do it…

Let's look at how to save an object to the database:

  1. The following code shows how we can 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.

How it works…

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:

  1. Get the SessionFactory.
  2. Open a new session.
  3. Begin a transaction.
  4. Create a department object.
  5. Save a department.
  6. Create an employee object.
  7. Set the saved department object as an employee department.
  8. Save an employee.
  9. Commit the transaction.
  10. Close the session.
  11. Close the SessionFactory.

There's more…

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

Note

Hibernate internally creates a core SQL query with the question mark (?) sign, which is actually replaced with the value of the field by hibernate.

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.

Note

While using this method, if the object is not found in the database against the passed value, hibernate throws an error related to the violation of the foreign key constraints.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.239.103