Cascade is used when multiple objects in entities wants to be saved in a single shot.

For Example

 session.save(objUserDetail1);
 session.save(objVeh1);
 session.save(objVeh2);
 session.save(objVeh3);

can be replaced by

 session.persist(objUserDetail1);

UserDetails.java

@Entity
@Table(name="USER_DETAIL")
public class UserDetails 
{	
	@Id @GeneratedValue(strategy = GenerationType.AUTO)	
	private int UserId;	
	private String UserName;
	
	@OneToMany(cascade=CascadeType.PERSIST)
	private List<Vehicles> arrVehicles = new ArrayList<Vehicles>();
	  
	public List<Vehicles> getArrVehicles() {
		return arrVehicles;
	}
	public void setArrVehicles(List<Vehicles> arrVehicles) {
		this.arrVehicles = arrVehicles;
	}
	
	public int getUserId() {
		return UserId;
	}
	public void setUserId(int userId) {
		UserId = userId;
	}
	public String getUserName() {
		return UserName;
	}
	public void setUserName(String userName) {
		UserName = userName;
	}
}

CreateTables.java

public static void main(String[] args) 
  {	
	UserDetails objUserDetail1 =  new UserDetails();
	objUserDetail1.setUserName("Mugil");

	Vehicles objVeh1 = new Vehicles();
	objVeh1.setVehicleName("Suzuki");
	objUserDetail1.getArrVehicles().add(objVeh1);

	Vehicles objVeh2 = new Vehicles();
	objVeh2.setVehicleName("Maruthi");
	objUserDetail1.getArrVehicles().add(objVeh2);

	Vehicles objVeh3 = new Vehicles();
	objVeh3.setVehicleName("Volkswagon");
	objUserDetail1.getArrVehicles().add(objVeh3);
							
	SessionFactory sessionFact = createSessionFactory();
	Session session = sessionFact.openSession();

	session.beginTransaction();				
	session.persist(objUserDetail1);		

	session.getTransaction().commit();
	session.close();  
  }

1.What is the difference between annotations @Id and @GeneratedValue

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id") 
private Integer id;

@Id
In a Object Relational Mapping context, every object needs to have a unique identifier. You use the @Id annotation to specify the primary key of an entity.

@GeneratedValue
The @GeneratedValue annotation is used to specify how the primary key should be generated. In your example you are using an Identity strategy which indicates that the persistence provider must assign primary keys for the entity using a database identity column.

Notes

  • The difference between @Id and @GeneratedValue can be clearly observed while switching from OneToOne and OneToMany Mapping where the OneToOne Mapping requires only ID to insert values for both the table whereas OneToMany Mapping table insertion depends on values inserted in one and other table.
  • @GeneratedValue creates a sequence maintained at database

2.Sequence vs Identity
Sequence and identity both used to generate auto number but the major difference is Identity is a table dependant and Sequence is independent from table.

If you have a scenario where you need to maintain an auto number globally (in multiple tables), also you need to restart you interval after particular number and you need to cache it also for performance, here is the place where we need sequence and not identity.

When @Id is used the value count starts from 0 where as when @GeneratedValue is used the count starts from 1

3.What is difference between OneToMany and ManyToOne Mapping?
For example, if a user, a company, a provider all have many addresses, it would make sense to have a unidirectional between every of them and Address, and have Address not know about their owner.

Suppose you have a User and a Message, where a user can have thousands of messages, it could make sense to model it only as a ManyToOne from Message to User, because you’ll rarely ask for all the messages of a user anyway.

In One-to-many you keep the reference of many objects via (set, list) for the associated objects. You may not access the parent object from the items it is associated with. E.g. A person has many skills. If you go to a particular skill you may not access the persons possessing such skills. This means given a Skill ,s, you’ll not be able to do s.persons.

In Many-to-one many items/objects will have reference to a particular object. E.g. Users x and y apply to some job k. So both classes will have their attribute Job job set to k but given a reference to the job k you many not access the objects that have it as an attribute job. So to answer the question “Which users have applied to the job k?”, you’ll have to go through the Users list.

One-to-Many: One Person Has Many Skills, a Skill is not reused between Person(s)
Unidirectional: A Person can directly reference Skills via its Set
Bidirectional: Each “child” Skill has a single pointer back up to the Person (which is not shown in your code)

One-to-Many: One Person Has Many Skills, a Skill is not reused between Person(s)
Unidirectional: A Person can directly reference Skills via its Set
Bidirectional: Each “child” Skill has a single pointer back up to the Person (which is not shown in your code)

Many-to-Many: One Person Has Many Skills, a Skill is reused between Person(s)
Unidirectional: A Person can directly reference Skills via its Set
Bidirectional: A Skill has a Set of Person(s) which relate to it.

4.Difference between Unidirectional and Bidirectional associations?
Bidirectional relationship provides navigational access in both directions, so that you can access the other side without explicit queries. Also it allows you to apply cascading options to both directions.

When we have a bidirectional relationship between objects, it means that we are able to access Object A from Object B, and Object B from Object A.

Unidirectional – means only allow navigating from one side of the mapping to another. For example in the case of a one-many mapping, only allow navigation from the one side to the many side. Bi-directional means to allow navigation both ways.

Continue reading

OnetoOne
UserDetails.java

@Entity
@Getter
@Setter
@Table(name="USER_DETAIL")
public class UserDetails 
{	
	@Id @GeneratedValue(strategy = GenerationType.AUTO)	
	private int UserId;	
	private String UserName;
	  
	@OneToOne
	private Vehicles veh;
}

Vehicles.java

@Entity
@Getter
@Setter
public class Vehicles 
{
	@Id @GeneratedValue
	private int vehicleId;
	
private String vehicleName;
}

CreateTable.java

public static void main(String[] args) 
  {
		UserDetails objUserDetail1 =  new UserDetails();
		objUserDetail1.setUserName("Mugil Vannan");
		
		Vehicles objVeh = new Vehicles();
		objVeh.setVehicleName("Suzuki");
		objUserDetail1.setVeh(objVeh);
		
		UserDetails objUserDetail2 =  new UserDetails();
		objUserDetail2.setUserName("Mani");
		
		Vehicles objVeh2 = new Vehicles();
		objVeh2.setVehicleName("Maruthi");
		objUserDetail2.setVeh(objVeh2);
		
		SessionFactory sessionFact = createSessionFactory();
		Session session = sessionFact.openSession();
		
		session.beginTransaction();				
		session.save(objUserDetail1);
		session.save(objVeh);
		session.save(objUserDetail2);
		session.save(objVeh2);
		session.getTransaction().commit();
		session.close();
  }

OnetoMany
UserDetails.java

@Getter
@Setter
@Entity
@Table(name="USER_DETAIL")
public class UserDetails 
{	
	@Id @GeneratedValue(strategy = GenerationType.AUTO)	
	private int UserId;	
	
        private String UserName;
	  
	@OneToMany	
        @JoinTable(joinColumns=@JoinColumn(name="USER_ID"),
	           inverseJoinColumns=@JoinColumn(name="VEHICLE_ID"))
	private List<Vehicles> arrVeh = new ArrayList<Vehicles>();
}

Vehicles.java

@Getter
@Setter
@Entity
public class Vehicles 
{
	@Id @GeneratedValue
	private int vehicleId;
	
        private String vehicleName;
}

CreateTables.java

 public static void main(String[] args) 
  {
        UserDetails objUserDetail1 =  new UserDetails();
        objUserDetail1.setUserName("Mugil Vannan");

        Vehicles objVeh = new Vehicles();
        objVeh.setVehicleName("Suzuki");
        objUserDetail1.getArrVeh().add(objVeh);

        Vehicles objVeh2 = new Vehicles();
        objVeh2.setVehicleName("Maruthi");
        objUserDetail1.getArrVeh().add(objVeh2);

        SessionFactory sessionFact = createSessionFactory();
        Session session = sessionFact.openSession();

        session.beginTransaction();				
        session.save(objUserDetail1);
        session.save(objVeh);
        session.save(objVeh2);
        session.getTransaction().commit();
        session.close();	
  }

ManytoOne
UserDetails.java

@Getter
@Setter
@Entity
@Table(name="USER_DETAIL")
public class UserDetails {	
	@Id @GeneratedValue(strategy = GenerationType.AUTO)	
	private int UserId;	
	
        private String UserName;
}

Vehicles.java

@Getter
@Setter
@Entity
public class Vehicles {
	@Id @GeneratedValue
	private int vehicleId;
	
        private String vehicleName;
	
	@ManyToOne	
	private UserDetails objUserDetails;
}

CreateTables.java

public static void main(String[] args) 
  {	
	Vehicles objVeh1 = new Vehicles();
        objVeh1.setVehicleName("Suzuki");

	Vehicles objVeh2 = new Vehicles();
	objVeh2.setVehicleName("Maruthi");

	UserDetails objUserDetail1 =  new UserDetails();
	objUserDetail1.setUserName("Mugil Vannan");
	
	objVeh1.setObjUserDetails(objUserDetail1);
	objVeh2.setObjUserDetails(objUserDetail1);
			
	SessionFactory sessionFact = createSessionFactory();
	Session session = sessionFact.openSession();

	session.beginTransaction();				
	session.save(objUserDetail1);		
	session.save(objVeh1);
	session.save(objVeh2);
	session.getTransaction().commit();
	session.close();	
  }

ManytoMany
UserDetails.java

@Getter
@Setter
@Entity
@Table(name="USER_DETAIL")
public class UserDetails {	
	@Id @GeneratedValue(strategy = GenerationType.AUTO)	
	private int UserId;	
	
        private String UserName;
	
	@ManyToMany
	private List<Vehicles> arrVehicles = new ArrayList<Vehicles>();
}

Vehicles.java

@Getter
@Setter
@Entity
public class Vehicles {
	@Id @GeneratedValue
	private int vehicleId;
	
        private String vehicleName;
	
	@ManyToMany(mappedBy="arrVehicles") 
	private List<UserDetails> arrUserDetails = new ArrayList<UserDetails>();
}

CreateTables.java

public static void main(String[] args) 
  {	
	Vehicles objVeh1 = new Vehicles();
	objVeh1.setVehicleName("Suzuki");
	
	Vehicles objVeh2 = new Vehicles();
	objVeh2.setVehicleName("Maruthi");
	
	UserDetails objUserDetail1 =  new UserDetails();
	objUserDetail1.setUserName("Mugil Vannan");
	
	UserDetails objUserDetail2 =  new UserDetails();
	objUserDetail2.setUserName("Mani");
	
	objVeh1.getArrUserDetails().add(objUserDetail1);
	objVeh1.getArrUserDetails().add(objUserDetail2);
	
	objUserDetail1.getArrVehicles().add(objVeh1);
	objUserDetail1.getArrVehicles().add(objVeh2);
							
	SessionFactory sessionFact = createSessionFactory();
	Session session = sessionFact.openSession();
	
	session.beginTransaction();				
	session.save(objUserDetail1);
	session.save(objUserDetail2);		
	session.save(objVeh1);
	session.save(objVeh2);
	session.getTransaction().commit();
	session.close();	
  }
   

@Entity
public class UserDetails 
{
@GenericGenerator(name="sequence-gen",strategy="sequence")
	@CollectionId(columns={@Column(name="Address_Id")}, generator="sequence-gen", type=@Type(type="long"))
private List<Address> arrList = new ArrayList<Address>();
.
.
.
}

While working with collection if you want the details to be stored in a seperate table using @ElementCollection solves the purpose

UserDetails.java

 public class UserDetails {
  @ElementCollection
  private List<Address> arrList = new ArrayList<Address>();

 }

Address.java

@Embeddable
public class Address 
{
  private String DoorNo;
  private String Street;
  private String Location;
  private String Pincode;
  .
  .
  .
 }

createTables.java

public class CreateTables {   
  public static void main(String[] args) 
  {
    UserDetails objUserDetail1 =  new UserDetails();

    Address objAddr = new Address();
    objAddr.setDoorNo("13");
    objAddr.setStreetName("Poes Road");
    objAddr.setLocation("Teynampet");
    objAddr.setPincode("600018");
    
    
    Address objAddr2 = new Address();
    objAddr2.setDoorNo("256");
    objAddr2.setStreetName("Sriman Srinivasan Road");
    objAddr2.setLocation("Alwarpet");
    objAddr2.setPincode("600018");
    
    objUserDetail1.getArrList().add(objAddr);
    objUserDetail1.getArrList().add(objAddr2);
  }
}

Giving Names to Joined Tables

  • New Table will be created under USER_ADDRESS Name
  • joinColumns decides which column should be used for joining two tables

Format for Join Table

  @JoinTable(name="JOIN_TABLE_DESIRED_NAME", 
	     joinColumns= @JoinColumn(name="userId"))
  @JoinTable(name="USER_ADDRESS", 
	     joinColumns= @JoinColumn(name="userId"))
  private Set<Address> addressSet = new HashSet();
  .
  .

Rows as Displayed in Screen

Rows from Database

Rows grouping Logic

	List<RowsBean> outputList = RowsToBeDisplayedList;		
	
	HashMap<String, ArrayList>  superGroupPoints    = new HashMap<String, ArrayList>();	
	HashMap<String, EWMDecimal> subGroupTotalPoints = new HashMap<String, Integer>();	
	
	String groupName = null;
	String prevGroupName = null;
	String superGroupName = null;
	String prevSuperGroupName = null;	
	
	List<Map> subGroupPointsList = new ArrayList();	
	
	
	//Compute grouping totals
	Iterator itr = cicCarryPointsList.iterator();
	
	 while(itr.hasNext()) 
	 {
		RowsBean rowBean = (RowsBean) itr.next();		
		superGroupName   = rowBean.getSuperGroupName();
		groupName 		 = rowBean.getGroupName();
		
  	        //Addition of points summed at Group Level
		if ((prevGroupName != null && !prevGroupName.equals(groupName))
				|| (prevSuperGroupName != null &&    !prevSuperGroupName.equals(superGroupName)))
		{
		   subGroupPointsList.add(subGroupTotalPoints);
		   subGroupTotalPoints = new HashMap<String, Integer>();
		}
		
		
		//Rows at GroupLevel with Sub Groups should be added only when Super Group Changes 
		if((prevSuperGroupName != null && !prevSuperGroupName.equals(superGroupName)))
		{			   
		   superGroupPoints.put(prevSuperGroupName, (ArrayList) subGroupPointsList);
		   subGroupPointsList = new ArrayList();
		}
		
		Integer subGroupValPoints = rowBean.getPoints();		    

		//If InvGrp level Map exists 
		if (subGroupTotalPoints.get(groupName) != null) {
			Integer currSummedPointsAtGrpLevel = subGroupTotalPoints.get(groupName);
			currSummedPointsAtGrpLevel = currSummedPointsAtGrpLevel.add(subGroupValPoints);
			subGroupTotalPoints.put(groupName, currSummedPointsAtGrpLevel);				
		} else {
			subGroupTotalPoints.put(groupName, subGroupValPoints);
		}
		
		//Incase of last element the loop exits without adding last summed element
		//To prevent that we add it with out current and prev comparison
		if(!itr.hasNext())
		{
			subGroupPointsList.add(subGroupTotalPoints);				
			superGroupPoints.put(superGroupName, (ArrayList) subGroupPointsList);
		}
		
		prevSuperGroupName = superGroupName;
		prevGroupName = groupName;
	}

Retrieval of Rows for Displaying in Screen

String currentSuperGrouping = "";
String prevSuperGrouping    = "";
String currGrouping = "";
String prevGrouping = "";
String Value = "";
 
for (RowsBean rowBean : outputList)
{
	currentSuperGrouping = rowBean.getSuperGroupName();
	currGrouping = rowBean.getGroupName();

    //Level 1 - New Super Group Creation 
	//New Super Group should be created when ever prevSuperGrouping and  currentSuperGrouping are different
    if (!currentSuperGrouping.equals(prevSuperGrouping))
    {
      .
      .  
      Super Group Row Creation HTML Code Goes Here
      .
      .
      .
    }
     
    //Level 2 - Group addition under Super Group
	//New Group should be created when ever SuperGroup or Group Changes
    if(!currGrouping.equals(prevGrouping) || !currentSuperGrouping.equals(prevSuperGrouping))
    {
      //Taking Group Level Maps List
      ArrayList GroupLevelMapList = superGroup.get(rowBean.getGroupName());
      Iterator  itr =  GroupLevelMapList.iterator();
       
	  //Taking the Summed up value at Group Level from List
      while (itr.hasNext())
      {
         Map ii = (Map) itr.next();
         Points = ii.get(rowBean.getGroupName());      
      }  
       
      .
      .  
      Group Row Creation HTML Code Goes Here
      .
      .
      .
    }
     
    //Level 3 - Sub Group Rows Addition
	//Rows will be added 
    if(currentSuperGrouping.equals(rowBean.getGroupName) || currentSuperGrouping.equals(rowBean.getSubGroupName))
    {
      .
      .  
      Sub Group Row Creation HTML Code Goes Here
      .
      .
      .
    } 
     
    prevSuperGrouping    = currentSuperGrouping;
    prevGrouping = currGrouping;
}

Java Bean Class – EmployeeBean

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class EmployeeBean {
	private String Name;
	private int EmpNo;
	private int Age;
	private float Weight;
	
	public String getName() {
		return Name;
	}
	public void setName(String name) {
		Name = name;
	}
	public int getEmpNo() {
		return EmpNo;
	}
	public void setEmpNo(int empNo) {
		EmpNo = empNo;
	}
	public int getAge() {
		return Age;
	}
	public void setAge(int age) {
		Age = age;
	}
	public float getWeight() {
		return Weight;
	}
	public void setWeight(float weight) {
		Weight = weight;
	}
	
	
	
	public EmployeeStringBean getStringBean() {
		
		EmployeeStringBean objEmpBean = new EmployeeStringBean();
		
		objEmpBean.setName(getName() == null?null:getName().toString());
		objEmpBean.setEmpNo(Integer.toString(getEmpNo()));
		objEmpBean.setAge(Integer.toString(getAge()));		
		objEmpBean.setWeight(getWeight()+"");
		
		return objEmpBean;
	}
	
	
	public static List getStringBeanList(List beanList) {
		 List stringBeanList = new ArrayList();

	        if (beanList != null) {
	            Iterator itr = beanList.iterator();

	            while (itr.hasNext()) {
	            	EmployeeBean bean = (EmployeeBean) itr.next();
	                stringBeanList.add(bean.getStringBean());
	            }
	        }

	        return stringBeanList;
	}
}

String Bean Class – EmployeeStringBean

public class EmployeeStringBean {
	private String Name;
	private String EmpNo;
	private String Age;
	private String Weight;
	
	public String getName() {
		return Name;
	}
	public void setName(String name) {
		Name = name;
	}
	public String getEmpNo() {
		return EmpNo;
	}
	public void setEmpNo(String empNo) {
		EmpNo = empNo;
	}
	public String getAge() {
		return Age;
	}
	public void setAge(String age) {
		Age = age;
	}
	public String getWeight() {
		return Weight;
	}
	public void setWeight(String weight) {
		Weight = weight;
	}	
	
	public EmployeeBean getBean()
	{
		EmployeeBean objEmployeeBean = new EmployeeBean();
		
		objEmployeeBean.setName(getName());
		objEmployeeBean.setEmpNo(Integer.parseInt(getEmpNo()));
		objEmployeeBean.setAge(Integer.parseInt(getAge()));
		objEmployeeBean.setWeight(Float.parseFloat((getWeight())));
		
		return objEmployeeBean;
	}	
}

While developing Java designers made a Mistake by allowing the static methods to get invoked by instance of a class.

someVariable.SomeMethod() I expect it to use the value of someVariable. If SomeMethod() is a static method, that expectation is invalid.

Language spec allows it like VB does and C# doesn’t.

class Base
{
    static void foo()
    {
        System.out.println("Base.foo()");
    }
}

class Derived extends Base
{
    static void foo()
    {
        System.out.println("Derived.foo()");
    }
}

public class Test
{
    public static void main(String[] args)
    {
        Base b = new Derived();
        b.foo(); // Prints "Base.foo()"
        b = null;
        b.foo(); // Still prints "Base.foo()"
    }
}

Whenever you submit a form to download a file the response sent back is a file. In this case the setter called after the method which does the download has no effect.

 if(form.getDownloadForm != null && form.getDownloadForm.equals("Y"))
 {
   downloadForm(form, request);

   //The Below Setter has No Effect
   form.setDownloadForm("Y");
 }
 class RegisterForm()
 {
   public String downloadForm;

    public void setDownloadForm(String p_download) 
    {
	  this.downloadForm= p_download;
    }
    
    public String getDownloadForm() 
    {
	  return downloadForm;
    }
 } 

The Setter had no effect since the request sent to the downloadForm(form, request); will end up with response of file download and not response which has new values to form set by setter(in our case downloadForm(form, request)) and Page reload.

There are 2 simple fix for this.

Fix 1
One simple fix is to set form hidden property in java script to N after the form get submitted. Note though the form is submitted it is not reloaded with new response since the response sent back is a file.

The Page will be reloaded only when response is sent back to the same URL of browser. Not to the browser as file.

 function downloadWFSetup(pWaterfallId) 
 {	
    $('#downloadForm').val('Y');
    document.WaterfallTriggerForm.submit();

    //This part of code runs even after the form submission since the 
    //response sent is file which does not require page reload
    $('#downloadForm').val('N');			
 }

In our case the page is not going to get reloaded so the java script continues its execution even after form submission setting property of downloadForm to N.

Fix 2
The Other way is to send request in Link with downloadForm=Y. In this case there is no need to to reset the form values as we get the values by request.getParameter() Method.