Hibernate for beginners | Hibernate Tutorial with Example | ORM tool

Hibernate for beginners | Hibernate Tutorial with Example | ORM tool



Hibernate is an Object/ Relational Mapping solution for Java environments. It reduces the development cost by reducing paradigm mismatch between how data is represented in objects versus relational databases.

Hibernate takes care of the mapping from Java classes to database tables and provides data query and retrieval facilities. This tutorial is designed for the beginners of Hibernate and expects you to have some knowledge about Java and SQL. I’m going to use MySQL database and Eclipse IDE in this tutorial.

By following this tutorial you will get the knowledge of;
1. Setup the Development Environment for Hibernate
2. Create POJO Classes
3. Create Mapping Files
4. Hibernate Configuration
5. Create Startup Helper Class
6. Create Test Class to Load and Store Objects

Let's start.

1. Setup the Development Environment for Hibernate

First you need to set up the development environment. Following things are needed if you want to try Hibernate with MySQL using Eclipse IDE.

1. Hibernate distribution bundle – Download
2. MySQL installed in your Computer – Download
3. JDBC driver for MySQL – Download
4. slf4j logging backend – Download
5. Eclipse IDE – Download

1.1 Setup the Database

I'm going to use simple database named "userdata" which has two tables named "users" and "tasks". Figure 1 illustrates the structure of the database and there "id" column is the Primary Key of both tables and it is set to AUTO_INCREMENT.

1.2 Create New Project

In this tutorial I’m going to show how to Retrieve, Add, Delete and Update data in a MySQL database. There I’ll create simple Java Project and you can use this tutorial to create web applications too.

First create new project in Eclipse using appropriate name, I’ll give "MyFirstHibernateApp".


You need to manually account for all the needed dependencies, so let’s create new folder called "lib" inside the "MyFirstHibernateApp" by right clicking on it as shown in following Figure 3.

Now copy following files into that folder.
1. hibernate3.jar (Can be found in distribution bundle)
2. All artifacts in the lib/required directory in distribution bundle
3. All artifacts in the lib/jpa directory in distribution bundle
4. All files from either the lib/bytecode/cglib or lib/bytecode/javassist directory
5. One of the slf4j logging (I'll use slf4j-simple-1.6.1.jar found inside slf4j-1.6.1.zip)
6. mysql-connector-java-5.1.15-bin.jar (JDBC driver for MySQL )

Then you can configure the built path. To do that, right click on project "MyFirstHibernateApp" in Package Explorer and select Build Path --> Configure Build Path... Then go to Libraries tab and browse lib folder you created earlier. Then add external jars by selecting all jar files that you copied to lib folder in one of previous step. (Check Figure 4).


Now you will be able to see the referenced libraries as follow (Figure 5).


2. Create POJO Classes

Next, I'll create two classes that represent the user and task we want to store in the database. Those are simple JavaBean classes with some properties which uses standard JavaBean naming conventions for property getter and setter methods and private visibility for the fields.

To create new class right click on "MyFirstHibernateApp" and select New --> Class. Then give appropriate package name, I’ll give "com.hib" as figure 6. You can generate getter and setters easily by selecting variable declaration and selecting Source --> Generate Getters and Setters…


User Class
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.hib;

public class User {
 private Integer id;
 private String firstName;
 private String lastName;
  
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
}
Task Class
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.hib;

public class Task {

 private Integer id;
 private Integer userID;
 private String title;
 private String description;
  
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public Integer getUserID() {
  return userID;
 }
 public void setUserID(Integer userID) {
  this.userID = userID;
 }
 public String getTitle() {
  return title;
 }
 public void setTitle(String title) {
  this.title = title;
 }
 public String getDescription() {
  return description;
 }
 public void setDescription(String description) {
  this.description = description;
 }
}
The id property holds a unique identifier value for a particular user and task. All persistent entity classes will need such an identifier property if you want to use the full feature set of Hibernate.

3. Create Mapping Files

Hibernate needs to know how to load and store objects of the persistent class. This is where the Hibernate mapping file comes into play. The mapping file tells Hibernate what table in the database it has to access, and what columns in that table it should use.

Right click on the "src" folder and select New --> File and paste following code there. Save it as user.hbm.xml.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

<hibernate-mapping>
 <class name="com.hib.User" table="users" >
  <id name="id" type="int" column="id" >
   <generator class="native"/>
  </id>

  <property name="firstName">
   <column name="first_name" />
  </property>
  <property name="lastName">
   <column name="last_name"/>
  </property>
 </class>
</hibernate-mapping>
Tasks.java should also have a mapping file, so create another file and paste following code. Save it as task.hbm.xml
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

<hibernate-mapping>
 <class name="com.hib.Task" table="tasks">
  <id name="id" type="int" column="id" >
   <generator class="native"/>
  </id>

  <property name="userID">
   <column name="user_id" />
  </property> 
  <property name="title">
   <column name="title" />
  </property>
  <property name="description">
   <column name="description"/>
  </property>
 </class>
</hibernate-mapping>
In the above mapping file you can see the mapping of the unique identifier property to the tables primary key. As we do not want to care about handling this identifier, we configure Hibernate's identifier generation strategy for a surrogate primary key column by giving class="native". If it is not AUTO_INCREMENT one we should use class="assign".

The id element is the declaration of the identifier property. The name="id" mapping attribute declares the name of the JavaBean property and tells Hibernate to use the getId() and setId() methods to access the property. The column attribute tells Hibernate which column of the "users" and "tasks" tables holds the primary key value. Similar to the id element, the name attribute of the property element tells Hibernate which getter and setter methods to use.

4. Hibernate Configuration

Now you have the persistent class and its mapping file in place. Let’s configure Hibernate.

Right click on the "src" folder and select New --> File and paste following code there. Save it as hibernate.cfg.xml. Here you have to give the username and password according to your MySQL account. In my case username is root and there is no password.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
<hibernate-configuration>
 <session-factory>
  <!-- Database connection settings -->
  <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="connection.url">jdbc:mysql://localhost/userdata</property>
  <property name="connection.username">root</property>
  <property name="connection.password"></property>
   
  <!-- JDBC connection pool (use the built-in) -->
  <property name="connection.pool_size">1</property>
   
  <!-- SQL dialect -->
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
   
  <!-- Enable Hibernate's automatic session context management -->
  <property name="current_session_context_class">thread</property>

  <!-- Disable the second-level cache -->
  <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</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">update</property>
   
  <!-- Mapping files -->
  <mapping resource="user.hbm.xml"/>
  <mapping resource="task.hbm.xml"/>
   
 </session-factory>
</hibernate-configuration>
5. Create Startup Helper Class

You have to startup Hibernate by creating a global org.hibernate.SessionFactory object and storing it somewhere for easy access in your application code. A org.hibernate.SessionFactory is used to obtain org.hibernate.Session instances. A org.hibernate.Session represents a single-threaded unit of work. The org.hibernate.SessionFactory is a thread-safe global object that is instantiated once. We will create a HibernateUtil helper class that takes care of startup and makes accessing the org.hibernate.SessionFactory more convenient.

To create new class right click on "com.hib" package and select New --> Class and give Name as HibernateUtil.java and paste the following code in class file.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.hib;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
 private static final SessionFactory sessionFactory = buildSessionFactory();
 private static SessionFactory buildSessionFactory() {
  try {
   // Create the SessionFactory from hibernate.cfg.xml
   return new Configuration().configure().buildSessionFactory();
  }
  catch (Throwable ex) {
   // Make sure you log the exception, as it might be swallowed
   System.err.println("Initial SessionFactory creation failed." + ex);
   throw new ExceptionInInitializerError(ex);
  }
 }
 public static SessionFactory getSessionFactory() {
  return sessionFactory;
 }
}
6. Create Test Class to Load and Store Objects

Now it’s time to do some real work using Hibernate. Following test class illustrate how we can Add, Retrieve, Update and Delete data in a MySQL database.

To create new class right click on "com.hib" package and select New --> Class and give Name as Test.java and paste the following code in class file.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package com.hib;

import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Test {

 /**
  * @param args
  */
 public static void main(String[] args) {
   
  Test tst = new Test();
   
  /**
   * adding records
   */
  tst.addUser("Saranga", "Rath");
  tst.addUser("Isuru", "Sampath");
  tst.addUser("Saranga", "Jaya");
  tst.addUser("Prasanna", "Milinda");
   
  tst.addTask(1, "Call", "Call Pubudu at 5 PM");
  tst.addTask(1, "Shopping", "Buy some foods for Kity");
  tst.addTask(2, "Email", "Send birthday wish to Pubudu");
  tst.addTask(2, "SMS", "Send message to Dad");
  tst.addTask(2, "Office", "Give a call to Boss");
   
  /**
   *  retrieving data
   */
  tst.getFullName("Saranga");
   
  /**
   * full updating records
   */
  User user = new User();
  user.setId(1);
  user.setFirstName("Saranga");
  user.setLastName("Rathnayake");
  tst.updateUser(user);
   
  /**
   * partial updating records
   */
  tst.updateLastName(3, "Jayamaha");

  /**
   * deleting records
   */
  User user1 = new User();
  user1.setId(4);
  tst.deleteUser(user1);
 }

 private void addUser(String firstName, String lastName) {
   
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
    
   User user = new User();
    
   user.setFirstName(firstName);
   user.setLastName(lastName);
    
   session.save(user);
    
   session.getTransaction().commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
 }

 private void addTask(int userID, String title, String description) {
   
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
    
   Task task = new Task();
    
   task.setUserID(userID);
   task.setTitle(title);
   task.setDescription(description);
    
   session.save(task);
    
   session.getTransaction().commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
 }
  
 private void updateLastName(int id, String lastName) {
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
   String hqlUpdate = "update User u set u.lastName = :newLastName where u.id = :oldId";
   int updatedEntities = session.createQuery( hqlUpdate )
   .setString( "newLastName", lastName )
   .setInteger( "oldId", id )
   .executeUpdate();

   trns.commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
   
 }

 private void updateUser(User user) {
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
    
   session.update(user);

   session.getTransaction().commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
 }

 private void getFullName(String firstName) {
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
   List<User> users = session.createQuery("from User as u where u.firstName = :firstName")
   .setString( "firstName", firstName )
   .list();
   for (Iterator<User> iter = users.iterator(); iter.hasNext();) {
    User user = iter.next();
    System.out.println(user.getFirstName() +" " + user.getLastName());
   }
   trns.commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
 }
  
 private void deleteUser(User user) {
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
    
   session.delete(user);

   session.getTransaction().commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
 }
}
If you have setup the database and followed the above steps correctly you should get following output.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Hibernate: insert into users (first_name, last_name) values (?, ?)
Hibernate: insert into users (first_name, last_name) values (?, ?)
Hibernate: insert into users (first_name, last_name) values (?, ?)
Hibernate: insert into users (first_name, last_name) values (?, ?)
Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?)
Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?)
Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?)
Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?)
Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?)
Hibernate: select user0_.id as id0_, user0_.first_name as first2_0_, user0_.last_name as last3_0_ from users user0_ where user0_.first_name=?
Saranga Rath
Saranga Jaya
Hibernate: update users set first_name=?, last_name=? where id=?
Hibernate: update users set last_name=? where id=?
Hibernate: delete from users where id=?
Hibernate use Hibernate Query Language (HQL) which is powerful than SQL and fully object-oriented. You can get good knowledge about HQL by following HQL Documentation.

I have included the source files of this tutorial with the database. You can download it from

When to use ConcurrentHashMap in Java | Key summary of ConcurrentHashMap | Java collection interview Question

ConcurrentHashMap is best suited when you have multiple readers and few writers. If writers outnumber reader, or writer is equal to reader, than performance of ConcurrentHashMap effectively reduces to synchronized map or Hashtable. Performance of CHM drops, because you got to lock all portion of Map, and effectively each reader will wait for another writer, operating on that portion of Map. ConcurrentHashMap is a good choice for caches, which can be initialized during application start up and later accessed my many request processing threads. As javadoc states, CHM is also a good replacement of Hashtable and should be used whenever possible, keeping in mind, that CHM provides slightly weeker form of synchronization than Hashtable.


Summary
Now we know What is ConcurrentHashMap in Java and when to use ConcurrentHashMap, it’s time to know and revise some important points about CHM in Java.

1. ConcurrentHashMap allows concurrent read and thread-safe update operation.

2. During update operation, ConcurrentHashMap only lock a portion of Map instead of whole Map.

3. Concurrent update is achieved by internally dividing Map into small portion which is defined by concurrency level.

4. Choose concurrency level carefully as a significant higher number can be waste of time and space and lower number may introduce thread contention in case writers overnumber concurrency level.

5. All operations of ConcurrentHashMap are thread-safe.

6. Since ConcurrentHashMap implementation doesn't lock whole Map, there is chance of read overlapping with update operations like put() and remove(). In that case result returned by get() method will reflect most recently completed operation from there start.

7. Iterator returned by ConcurrentHashMap is weekly consistent, fail safe and never throw ConcurrentModificationException. In Java.

8. ConcurrentHashMap doesn't allow null as key or value.

9. You can use ConcurrentHashMap in place of Hashtable but with caution as CHM doesn't lock whole Map.

10. During putAll() and clear() operations, concurrent read may only reflect insertion or deletion of some entries.

That’s all on What is ConcurrentHashMap in Java and when to use it. We have also seen little bit about internal working of ConcurrentHashMap and how it achieves it’s thread-safety and better performance over Hashtable and synchronized Map. Use ConcurrentHashMap in Java program, when there will be more reader than writers and it’s a good choice for creating cache in Java as well.

Diffrence between Spring MVC and Struts MVC | MindMill Software Ltd interview question 2013

Date of interview 21 Feb 2013

In technical round they asked to tell difference between Spring MVC and Struts MVC

Spring is a powerful Java application framework, used in a wide range of Java applications. It provides enterprise services to Plain Old Java Objects (POJOs). Spring uses dependency injection to achieve simplification and increase testability.
1. Spring provides a very clean division between controllers, JavaBean models, and views.
2. Spring’s MVC is very flexible. Unlike Struts, which forces your Action and Form objects into concrete inheritance (thus taking away your single shot at concrete inheritance in Java), Spring MVC is entirely based on interfaces. Furthermore, just about every part of the Spring MVC framework is configurable via plugging in your own interface. Of course we also provide convenience classes as an implementation option.
3. Spring, like WebWork, provides interceptors as well as controllers, making it easy to factor out behavior common to the handling of many requests.
4. Spring MVC is truly view-agnostic. You don’t get pushed to use JSP if you don’t want to; you can use Velocity, XLST or other view technologies. If you want to use a custom view mechanism – for example, your own templating language – you can easily implement the Spring View interface to integrate it.
5. Spring Controllers are configured via IoC like any other objects. This makes them easy to test, and beautifully integrated with other objects managed by Spring.
6. Spring MVC web tiers are typically easier to test than Struts web tiers, due to the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet.
7. The web tier becomes a thin layer on top of a business object layer. This encourages good practice. Struts and other dedicated web frameworks leave you on your own in implementing your business objects; Spring provides an integrated framework for all tiers of your application.
8. No ActionForms. Bind directly to domain objects
9. More testable code (validation has no dependency on Servlet API)
10. Struts imposes dependencies on your Controllers (they must extend a Struts class), Spring doesn’t force you to do this although there are convenience Controller implementations that you can choose to extend.
11. Spring has a well defined interface to business layer
12. Spring offers better integration with view technologies other than JSP (Velocity / XSLT / FreeMarker / XL etc.)
 

Error Cannot find ActionMappings or ActionFormBeans collection , Cannot retrieve mapping for action in Struts 1.2.

Cannot find ActionMappings or ActionFormBeans collection  , when he access the login.jsp of  the application deployed in WebSphere Application Server (WAS)  running on the Linux server. The application was developed using the framework  struts 1.2 and the application works fine with ide WSAD. The above error is thrown when the application server executes the  following line

<html:form name="loginForm" type="Sales.login.LoginForm" method="post" scope="request" action="/login.do" onsubmit="return submitForm()" >
 

The above error may occur due to various reasons.

Some of the situations  where the error may be thrown are as follows

Situation 1 :  When the Request Processor  searches for  the mapping of  this request, if  it is not able to  find the mappings that  are defined in the struts-config.xml , the following errors may be thrown depending upon the situation.

a)  If  the server is able to load the struts-config.xml , but the   mapping  is not available in the struts-config.xml . for eg.  if  the JSP has  <html:form action="/login" method="post" type="LoginAction">
                         then your struts-config.xml should have mapping for action parameter i.e. "/login"  something like

<action-mappings>
    <action path="/login"        type="LoginAction"    name="loginForm"          scope="request"       validate="false"   input="/login.jsp" >
     </action>
</action-mappings>


But if the mapping is not present in the   struts-config.xml , then you may get the error    [Cannot retrieve mapping for action /login1]: javax.servlet.jsp.JspException: Cannot retrieve mapping for action /login

b) But the above mapping is present in the struts-config.xml  , but you are getting the error  Cannot find ActionMappings or ActionFormBeans collection   ,  That means the sever is not able to load the struts-config.xml fle.

 To solve , the above problem ,  Please ensure , the path & file name of struts-config.xml file mentioned in the web.xml file  is correct and case sensitive.

  In our  case , the problem was very silly and the problem got solved when i  add a slash (/) infront of WEB-INF ...

The belows lines are part of the web.xml and the param-value  to be passed to  ActionServlet is wrongly mentioned

<servlet>
   <servlet-name>action</servlet-name>
   <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
   <init-param>
    <param-name>config</param-name>
    <param-value>WEB-INF/struts-config.xml</param-value>   OR   <param-value>/web-inf/struts-config.xml</param-value>    // Wrong
   </init-param>
 

In the above lines  , changing  the line   <param-value>WEB-INF/struts-config.xml</param-value> OR  <param-value>web-inf/struts-config.xml</param-value>  to

<param-value>/WEB-INF/struts-config.xml</param-value>  , will solve the problem


Situation 2 :   If   the sever is able to load the struts-config.xml fle and also the  mapping is present in the struts-config.xml , then the Request Processor does  process  any ActionForm bean related to this request. (i.e. finding , loading  the ActionFormBeans collection, ..etc ) .

             Various classes such as org.apache.struts.action.ActionFormBeans ,  org.apache.commons.collections.FastHashMap   are involved for the above process.  And the following jars are  involved
                  struts.ear
                  commons-collections.jar
                   commons-beanutils.jar

  ....
  .....
            So  If you miss the jar files such as    commons-collections.jar  , commons-beanutils.jar in the class path , then the request processor may not find the ActionFormBeans collection , and the error Cannot find ActionMappings or ActionFormBeans collection  is thrown

Generics in Java | How to write parametrized class and method in Java | java Generics interview Question answer

Before to going start how write  parametrized class and method in Java . i would like to give some important fact about generic

1. java generic has introduced with JDK 1.5 along with Autoboxing, varargs, ,Enum
2. Generics  provide compile-time type safety that allows programmers to catch invalid types at compile time.
3. Not only can Java generics be used in fields and methods, it can also be used in class definitions to produce parameterized classes.


How to write  parametrized class

1. A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section.

2. As with generic methods, the type parameter section of a generic class can have one or more type parameters separated by commas.

public class Member<T> {
 private T id;
 public Member(T id) {
   this.id = id;
 }
 public T getId() {
   return id;
 }
 public void setId(T id) {
   this.id = id;
 }
 public static void main(String[] args) {
   Member<String> mString = new Member<String>("id1");
   mString.setId("id2");
   System.out.printf("id after setting id: %s%n", mString.getId());
   //output:  id after setting id: id2
 
   Member<Integer> mInteger = new Member<Integer>(1);
   mInteger.setId(2);
   System.out.printf("id after setting id: %d%n", mInteger.getId());
   //output:  id after setting id: 2
 }


How to write parametrized method

 1.All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example).

    2. Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type        name.

   3.  The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type        arguments.

   4.  A generic method's body is declared like that of any other method. Note that type parameters can represent only reference types not primitive types (like int, double and char).

public class GenericMethodTest
{
   // generic method printArray                        
   public static < E > void printArray( E[] inputArray )
   {
      // Display array elements             
         for ( E element : inputArray ){       
            System.out.printf( "%s ", element );
         }
         System.out.println();
    }

    public static void main( String args[] )
    {
        // Create arrays of Integer, Double and Character
        Integer[] intArray = { 1, 2, 3, 4, 5 };
        Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
        Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

        System.out.println( "Array integerArray contains:" );
        printArray( intArray  ); // pass an Integer array

        System.out.println( "\nArray doubleArray contains:" );
        printArray( doubleArray ); // pass a Double array

        System.out.println( "\nArray characterArray contains:" );
        printArray( charArray ); // pass a Character array
    }
}

Java Clone() concept | how clone work in java | java clone interivew question answer

First of all Java clone() method has given in Object class with below
protected Object clone() throws CloneNotSupportedException

with above definition some time in interview question you will found like
  • Why clone() method has given in Object class
  • What is the reason behind to make clone() method protected
  • What meaning of CloneNotSupportExeption
  • What is Shallow cloning and deep cloning

Definition
Clone() method is used to create a copy of an object of a class which implements Cloneable interface. By default it does field-by-field copy as the Object class doesn't have any idea in advance about the members of the particular class whose objects call this method. So, if the class has only primitive data type members then a completely new copy of the object will be created and the reference to the new object copy will be returned. But, if the class contains members of any class type then only the object references to those members are copied and hence the member references in both the original object as well as the cloned object refer to the same object.

Use of Cloneable interface
 
We get CloneNotSupportedException if we try to call the clone() method on an object of a class which doesn't implement the Cloneable interface. This interface is a marker interface and the implementation of this interface simply indicates that the Object.clone() method can be called on the objects of the implementing class.

Java clone() concept


1. Objects in Java are referred using reference types, and there is no direct way to copy the contents of an object into a new object.  The assignment of one reference to another merely creates another reference to the same object.
2.  When you don't want to modify the method caller's (or original) object.
 Different analysis on same set of data in an Object. Rather than fetching the data again and again, populate object once and clone it for a new analysis.
 Games - walls, doors, cars graphics - clone the object, change the params.
3.For any class to able to be cloned .clone() - it MUST implement java.lang.Cloneable interface. Otherwise is .clone is used, it throws java.lang.CloneNotSupportedException at runtime.
  It is a marker interface - which simply tells JVM that the Object.clone() method can be called on the objects of this or sub classes.
4. Shallow Copy - see clone() method in below code
 This is a result of the default cloning functionality provided by the Object.clone()
 When this is used, it copies the primitives and the references. Only references are copied to new cloned Object. Actual referenced object remains as it. That means, the member references in original and cloned object - point to same object.
 
5.  Deep Copy - see deepClone() method in below code
 Copy the actual member objects along with primitives and member references.
 We need to override the clone() method in order to achieve it. But need to make sure that member Objects that we are trying to copy, should also implement Cloneable, only then then can be cloned.
 
 
public class Clones {
public static void main(String[] args) throws CloneNotSupportedException {
Person p1 = new Person("AAA", 123, 100, 200);
System.out.println("Original");
System.out.println(p1.salary.basic);
Person p2 = (Person) p1.deepClone();
//p2.name = "BBB";
//p2.salary.basic = 2222;
System.out.println(p1.equals(p2));
System.out.println("Clone");
System.out.println(p2.salary.basic);
System.out.println("Original");
System.out.println(p1.salary.basic);
}
}
// cloneable class implements Cloneable
class Person implements Cloneable {
public String name = null;
public int id = 0;
public Salary salary = null;
public Person(String name, int id, int basicSal, int bonusSal) {
this.name = name;
this.id = id;
// using Object type member to test for cloning
Salary sal = new Salary();
sal.basic = basicSal;
sal.bonus = bonusSal;
this.salary = sal;
}
// shallow copying
protected Object clone() throws CloneNotSupportedException {
// This is default cloning provided by the Object.clone()
return super.clone();
}
// deep copying
protected Object deepClone() throws CloneNotSupportedException {
// The clone() method produces an Object, which must be recast to the proper type
Person p = (Person) super.clone();
// In deep cloning, we also clone the member objects, but for this to work - //member objects should be Cloneable
p.salary = (Salary) p.salary.clone();
return p;
}
}
// member object of Person class as Cloneable. If it was not, then deep cloning //would not have been possible
class Salary implements Cloneable {
public int basic = 0;
public int bonus = 0;
public int getSalary() {
return basic + bonus;
}
// implementing clone()
protected Salary clone() throws CloneNotSupportedException {
Salary s = (Salary) super.clone();
return s;
}
}
// Cloneables with final fields - not meant go together. No error, but when try //to change, it cribs.
// The only solution is to remove the final modifier from the field, giving up //the benefits the modifier conferred.

Java interview question related Session listner, web services in MNC software company

Below Few Java interview question asked at MNC software company

1. How can you count active sessions by using listeners in JAVA.

we can do it by using HttpSessionListener for that you can create a session count class implementing HttpSessionListener interface. Our listener object will be called every time a session is created or destroyed by the server. You can find more information about HttpSessionListener at When do I use HttpSessionListener?.
 
Code  example,
 we have MySessionCounter.java that implements HttpSessionListener interface. We implement sessionCreated() and sessionDestroyed() methods, the sessionCreated() method will be called by the server every time a session is created and the sessionDestroyed() method will be called every time a session is invalidated or destroyed.


package com.xyzws.web.utils;

import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionEvent;

public class MySessionCounter implements HttpSessionListener {

private static int activeSessions = 0;

public void sessionCreated(HttpSessionEvent se) {
activeSessions++;
}

public void sessionDestroyed(HttpSessionEvent se) {
if(activeSessions > 0)
activeSessions--;
}

public static int getActiveSessions() {
return activeSessions;
}


To receive notification events, the implementation class MySessionCounter must be configured in the deployment descriptor for the web application. add <listener> section into our /WEB-INF/web.xml file:

   <!-- Listeners -->  <listener>    <listener-class>com.xyzws.web.utils.MySessionCounter</listener-class>  </listener>

For show in JSP
 the following JSP code shows the total active session:
 <%@ page import="com.xyzws.utils.MySessionCounter"%><html>...  Active Sessions : <%= MySessionCounter.getActiveSessions() %>...</html>

2) what is XML schema and it tags??
 
Definition
An XML Schema defines and describes certain types of XML data by using the XML Schema definition language (XSD). XML Schema elements (elements, attributes, types, and groups) are used to define the valid structure, valid data content, and relationships of certain types of XML data. XML Schemas can also provide default values for attributes, and elements.


XML Schema has contains below :

  • The first statement, <?xml version="1.0" encoding="utf-8"?>, specifies the version of XML in use.

  • The second statement consists of several parts:

The xs:schema declaration indicates that this is a schema and that the xs: prefix will be used before schema items.

The xmlns:xs="http://www.w3.org/2001/XMLSchema" declaration indicates that all tags in this schema should be interpreted according to the default namespace of the World Wide Web Consortium (W3C), which was created in 2001.

The targetnamespace declaration names this schema as XMLSchema1.xsd and indicates its default location, which will be in a default URI (universal resource identifier) on your development server called tempuri.org.

When you create a schema with the XML Designer, the version and namespace statements are automatically added for you. You might modify the contents of these two declarations in some cases. For example, if you want to use a tag prefix other than "XS," you would need to define the default namespace for that tag in addition to the XS tag prefix.

A complex type called "addressType" is defined that will contain five elements of various data types. Note that each of the elements it contains is a simple, named type.


Example

How to write XML schema of below requirments
The final element in the purchaseOrder, Item, contains a facet called maxOccurs. Facets set limits on the type of content a simple type can contain. maxOccurs is used to constrain how many times an element can occur in the documents created from this schema. By default, maxOccurs is equal to one. In this case, setting it to unbounded indicates that the Item element can reoccur as many times as needed.

<?xml version="1.0" encoding="utf-8"?>
<xs:schema targetNamespace="http://tempuri.org/XMLSchema1.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:complexType name="addressType">
   <xs:sequence>
      <xs:element name="street1" type="xs:string"/>
      <xs:element name="street2" type="xs:string"/>
      <xs:element name="city" type="xs:string"/>
      <xs:element name="state" type="xs:string"/>
      <xs:element name="zip" type="xs:integer"/>
   </xs:sequence>
</xs:complexType>

<xs:element name="purchaseOrder">
      <xs:complexType>
         <xs:sequence>
            <xs:element name="shipTo" type="addressType" />
            <xs:element name="billTo" type="addressType" />
            <xs:element name="shipDate" type="xs:date" />
            <xs:element name="item" maxOccurs="unbounded"/>
         </xs:sequence>
      </xs:complexType>
   </xs:element>
</xs:schema>