Wednesday, June 12, 2013

16 - CascadeTypes and Other Things



In this tutorial, we'll look at some concepts like CascadeType which can be configured for entity relationships.

Cascade is a convenient feature to save the lines of code needed to manage the state of the other side manually.
  1. inverse: This is used to decide which side is the relationship owner to manage the relationship (insert or update of the foreign key column). 
  2.  cascade: In cascade, after one operation (save, update and delete) is done, it decide whether it need to call other operations (save, update and delete) on another entities which has relationship with each other.
Conclusion: In short, the “inverse” is decide which side will update the foreign key, while “cascade” is decide what’s the follow by operation should execute. Both are look quite similar in relationship, but it’s totally two different things. Hibernate developers are worth to spend time to research on it, because misunderstand the concept or misuse it will bring serious performance or data integrity issue in your application.

If relationship not found ignore error

@NotFound(action=NotFoundAction.IGNORE)


HibernateTest.java

package org.yash.hibernate;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.yash.dto.UserDetails;
import org.yash.dto.Vehicle;

public class HibernateTest {

      public static void main(String args[]){
            UserDetails user = new UserDetails();
            user.setUserName("First User");
           
            Vehicle vehicle = new Vehicle();
            vehicle.setVehicleName("Car");
            Vehicle vehicle2 = new Vehicle();
            vehicle2.setVehicleName("Jeep");
           
            user.getVehicle().add(vehicle);
            user.getVehicle().add(vehicle2);

            SessionFactory sessionFactory =
new Configuration().configure().buildSessionFactory();           
            Session session = sessionFactory.openSession();
            session.beginTransaction();
           
            session.persist(user);
           
            session.getTransaction().commit();
            session.close();

      }
}

UserDetails.java
package org.yash.dto;

import java.util.ArrayList;
import java.util.Collection;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="USER_DETAILS")
public class UserDetails {
      /* @Id says "userId" is primary key */
      @Id @GeneratedValue (strategy=GenerationType.AUTO)
      private int userId;    
      private String userName;
      @OneToMany(cascade=CascadeType.PERSIST)
      private Collection<Vehicle> vehicle = new ArrayList<Vehicle>();
           
      public int getUserId() {
            return userId;
      }
      public void setUserId(int userId) {
            this.userId = userId;
      }
      public String getUserName() {
            return userName;
      }
      public void setUserName(String userName) {
            this.userName = userName;
      }
      public void setVehicle(Collection<Vehicle> vehicle) {
            this.vehicle = vehicle;
      }
      public Collection<Vehicle> getVehicle() {
            return vehicle;
      }
}


Vehicle.java
package org.yash.dto;

import java.util.ArrayList;
import java.util.Collection;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

@Entity
public class Vehicle {
      @Id @GeneratedValue
      private int vehicleId;
      private String vehicleName;
      @ManyToMany(mappedBy="vehicle")
      private Collection<UserDetails> userList =
new ArrayList<UserDetails>();

      public int getVehicleId() {
            return vehicleId;
      }
      public void setVehicleId(int vehicleId) {
            this.vehicleId = vehicleId;
      }
      public String getVehicleName() {
            return vehicleName;
      }
      public void setVehicleName(String vehicleName) {
            this.vehicleName = vehicleName;
      }
      public void setUserList(Collection<UserDetails> userList) {
            this.userList = userList;
      }
      public Collection<UserDetails> getUserList() {
            return userList;
      }
}

hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <property name="connection.driver_class">
            org.postgresql.Driver
        </property>
        <property name="connection.url">
            jdbc:postgresql://localhost:5433/hibernatedb
        </property>
        <property name="connection.username">postgres</property>
        <property name="connection.password">admin</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">
            org.hibernate.dialect.PostgreSQLDialect
        </property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
       
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
       
        <!-- Drop and re-create the database schema on startup -->
            <property name="hbm2ddl.auto">create</property> 
<!-- create / update -->
   
          <!-- Names the annotated entity class -->
            <mapping class="org.yash.dto.UserDetails"/>    
            <mapping class="org.yash.dto.Vehicle"/>  
           
    </session-factory>

</hibernate-configuration>
 

No comments:

Post a Comment