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();
  .
  .

FOR cur IN (SELECT  process_Id 
              FROM  tbl_process)
LOOP
  SELECT (MAX(TO_NUMBER(substr(p.old_id, instr(p.old_id, '_', -1) + 1))))
    INTO new_id
    FROM tbl_process p
   WHERE process_Id = cur.process_Id;

  IF new_id IS NULL THEN
    new_id := cur.process_Id || '_1';
  ELSE
    new_id := new_id + 1;
    new_id := cur.process_Id || '_' || new_id;
  END IF;
END LOOP;

If you want a query which returns rows in column containing NULL or empty space then the using NULL alone in where clause will not return empty space rows. So the query should be altered as below

Actual Query

 SELECT COUNT (*) 
   FROM TABLE 
  WHERE COL_NAME IS NULL;

Altered Query

  SELECT COUNT (*) 
    FROM TABLE 
   WHERE trim(COL_NAME) IS NULL

(or)

Altered Query

  SELECT COUNT (*) 
    FROM TABLE  
    WHERE COL_NAME IS NULL OR 
          LENGTH(TRIM (COL_NAME)) = 0

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;
}

      Right Click on build.xml
      Go to “Run As” >> “External Tools Configurations…”
      It shall open new window
      Go to JRE tab
      Select proper JRE if missing (sometimes jre tabs shows error mark on that.)