After installing java and setting the path for it now its turn to have some fun with codes. Now i am going to tell you how to print your text in java. Its a very simple program and basically for beginners. There are some important concept of packages in java and i m going to use that package concept in my program just to make you aware for this. We will see the details in their respective topics.


First program in java to print a simple text !


import java.lang.Object;



public class FirstProgram{



public static void main(String arg[]) {


System.out.println(" This is my first program in java " );

    }

}

Write the above program in a text editor like notepad and save it as the name of your class_name , here it is FirstProgram. So you must save it as,
FirstProgram.java

After saving now you can compile and run the above code in command prompt like this,
First go to directory where you saved your program and then , run code like this,

javac  FirstProgram.java

java  FirstProgram

Output:- This is my first program in java

In the above program there is something interesting which you should know i.e ,
1) The use of import keyword ( Line 1 in the above program)
2)  Use of public keyword before class ( Line 2 )
3) Use of main() method ( Line 3 )
4) Use of System.out.println() ( Line 4 )

Import keyword :- Import statement must be the first statement in java , it can't be the 2nd or any other because while compiling java code, compiler must know which class is going to import. By using import statement you are going to tell compiler to import the classes available on that package before writing any other statements. For now you just keep remember that package is the collection of predefined classes and within that classes there are many methods defined which we are going to use in our code for building the application. So compiler must know about which packages is to import. For details in Import statement Click Here ! 

Here, in the above program i used java.lang.Object , it means i m using java.lang which is a package and Object which is a class in this full import statement. And import keyword must be written in lower case.
You can have multiple import statement and must be terminated by semi-colon( ; ).

Syntax for import statement :- import <package_ name>; 

Note: If you are not writing / maintaining any package then by default it will import java.lang.Object. 
so we can say that java.lang.Object is a default package in java.

Public keyword :- In java, public is an access modifier. It tells about the accessibility scope, that scope may be for a variable/methods/class etc . And we are allowed to use only one public class in a single program.If there are two Public classes in a single program then it would be difficult for compiler to identify which public class name is used as to save as our program name. But it is not necessary that your program must contain at least one public class, but its mandatory that there should be only one public class if you are defining any public class in java and program name should be as the name of the public class. For details regrading this topic must read out saving java files topic later in this tutorial.

I you are not using any public access modifier before class that means it is be default " Default " which is one of the access modifier in java.

Syntax for using public access modifier:-

public class <class_name>{}

Main() method :- Main method in java is indicating as the starting point of the execution of your program. You can have multiple main() method but the point is that it should be in different class. Means one class can't accommodate two main() method, will give you a compilation error.
In short one class can have only one main() method. And a program may contain more then one class so we can define main() method for each classes, it means our java program can contain more than one main() method, it won't give any compilation error but the execution of the main() method depends on the program name which is one of the class you defined in your program.

If you have multiple class and in each class you have one main method then JVM is going to execute the main method of that class which is saved as a program name. But again it is going to execute the other classes main method only when you mention that class name while executing ( not compiling) your program by the JVM. If you have confused then will make it clear in execution of main() method topic later in this tutorial.


What is that string we are passing as an argument? and 
Why we are defining static to the main() method?

To clear all these doubts regrading the main() method Click Here !

System.out.println :- Here in this statement, System is a class where as out is the print stream and println() is the method for printing the text defined withing inverted  commas   ( " " ).

Why we have used the above statement like this?
--> It is because to indicate the compiler that println() is a method of System class and out is the print stream of System class.
Today I am going to tell you other alternative you can do in order to avoid LazyInitializationException: Session has been closed. If you are using SPRING with HIBERNATE that you can take the advantages of IOC and AOP. These are some functions that you must have to know in order to understand the working of this concept.

session.connect() : It is a function that will be called on a Session object it is responsible for establishing the connection with the database.

session.disconnect() : It will release the connection resources. It doesn't mean you are closing the connection.

session.flush() : this function is used to serialize the data to the database. If you have something in the session that is not submitted to DB you can submit them using session.flush().

So here is the utility class that you can take :

HibernateUtil.java 

public class HibernateUtil {
    @Autowired
    private static SessionFactory sessionFactory;
    private static final ThreadLocal threadsession=new ThreadLocal();
    private static final ThreadLocal threadtransaction=new ThreadLocal();
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    public void connect() {
        try {
            Session session=threadsession.get();
            if(session==null) {
                getSession();
                session=threadsession.get();
            }
            session.reconnect();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
    public void diconnect() {
        Session session=threadsession.get();
        session.disconnect();
    }
    public Session getSession()    {
        Session session=threadsession.get();
        try {
            if(session==null) {
                session=sessionFactory.openSession();
                threadsession.set(session);
            }
        }
        catch(Exception e) {
            e.printStackTrace();
        }
        return session;
    }
    public void closeSession() {
        try {
            Session session=threadsession.get();
            threadsession.set(null);
            if(session!=null && session.isOpen())
                session.close();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
    public void beginTransaction() {
        Transaction tx=threadtransaction.get();
        try {
            if(tx==null) {
                tx=getSession().beginTransaction();
                threadtransaction.set(tx);
            }
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
    public void commitTransaction() {
        Transaction tx=threadtransaction.get();
        try {
            if(tx!=null && !tx.wasCommitted() && !tx.wasRolledBack())
                tx.commit();
            threadtransaction.set(null);
        }
        catch(Exception e) {
            rollbackTransaction();
            e.printStackTrace();
        }
    }
    public void rollbackTransaction() {
        Transaction tx=threadtransaction.get();
        try {
            threadtransaction.set(null);
            if(tx!=null && !tx.wasCommitted() && !tx.wasRolledBack()) {
                tx.rollback();
            }
        }
        catch(Exception e) {
            e.printStackTrace();
        }
        finally {
            closeSession();
        }
    }
}

You can easily understand the HibernateUtil class we have use the Thread Local design pattern that you can see her.
I am taking one interceptor from where we can call the functions from out utility class and you can call it by using AOP.
here is the code that you can apply on your service layer using AOP.

ConnectionService.java

public class ConnectionService {

 @Autowired
 HibernateUtil2 hutil;
 public void startConnection() {
  hutil.connect();
  hutil.beginTransaction();
  System.out.println("before");
 }
 public void closeConnection() {
  System.out.println("after");
  hutil.commitTransaction();
  hutil.diconnect();
  hutil.getSession().flush();
 }
}


Now you have to configure this in spring configuration file and you have done.
LazyInitializationException: Session has been closed
Like all other programming language it is also a well known programming language basically designed for web application . As we all know that c++ is an objected oriented language but not fully object oriented, an attempt made by the java programmers to make it full / pure object oriented language and some how it satisfies but still it is not a pure object oriented language as just because we are still using primitive data types ( int, float, long, char etc) but there is a concept of wrapper class  by which we can be able to use primitive types as an object which was again a close attempt to make it a pure object oriented .

Wrapper Class --> It is a class by which we can be able to create the Object of primitive data types. Will see in details about the wrapper class later in this tutorial.

Ex- for int there is a class defined in java called as Integer which is formally called as wrapper class.
Like this for every primitive data type there is wrapper class.

What is the advantage of Java ?

Well we all know that java is a compiled and interpreted both. Compiled means checking the errors by the java compiler at the compilation and where as interpreted means running the successfully compiled codes. Now you must think that what is the benefit of doing like this even compiling and interpreting will take more time but it introduced a new concept of portability .

How and why Java are portable ?
Let me tell you when we compiler our java program , java compiler checks the error and produces the .class file. Now you all must be thinking of what is this .class file?

What is .class file?  
It is a file created after successful compilation. Our source code contain the high level definition but after compilation it get converted into machine readable code which is a .class file. And then JVM ( Java Virtual Machine) will run the .class file and gives us our desired result.

So portability on java means we can run this .class file in any system , the only need is to have JDK installed in our system for interpreting . class file. So from there is no need of installing compiler for all other system in which you are going to run your code. Only we need is compatible JDK for the specific System.

javac--- java compiler used for compiling the java source file.

java-- java interpreter used for interpreting the .class file.

Now let me give you some brief information about the most used terms / concept in Java.
Details for the same we will see later in this tutorial. Some of the terms / concepts are as follows:-

1) Object :- We can call it as the base of java, i want to say that Java is fully based on object, it means we are going to use only object for all our purposes. Here is the link to study in detail about object in java Object in Details .

2) Class :- We can call class as blue print of object. It will define the structure , means where we are going to define the variable, objects and many more. So it just give you the way to use the members, methods, objects etc.

 3) Data types:- Data types are the keywords / user defined class/ interfaces in java.
 Here keyword means there are few keywords like int, float etc which defines the memory for the variable and also with its specific size and scope. For details about Data types in java Click Here .

And user defined class/ interfaces means we can define our own data types for our own purposes.
So class and interfaces are called as user defined data types.

In java according to the data representation we are having only two types:-
1) Primitive / base data types  ( int. float. long. char etc).
2) Reference data type ( String, array, object etc).

4) Static : Basically static is a keyword in java. And it is not the scope of the object. Means not need to create an object to access the static members / methods, instead it can be easily accessible by the class name. And for static members only once the memory is created. Will look for this in details in its topic.
Why we donot need to create an object to access the static members and how is it possible by the class name?
To know about the above question and detailed explanation about the static then Click here .



Setting PATH and CLASSPATH are two different task in Java. Let me make you more clear about PATH setting and CLASSPATH setting in Java. If you had missed your lectures on PATH setting then this post will make you clear view about PATH setting . 

PATH ---> It is the path indicating the lists of all java executable files which will be use to run our java programs.

CLASSPATH ----> It is the path indicating the lists of all class file of the users, it has nothing to do with java predefined classes. It only indicates where the user class file is present.

What is the need of setting PATH ?

PATH is a system variable predefined in the windows OS . It must be written in capital letters and we need of set path of the Java executable files ( like Javac.exe, java.exe , javadoc.exe etc ). It is because unless we set the path we can't be able to run the java program.

Now you must be thinking of that , 
Is it possible to run java programs without setting the path ?

Answer is yes, you can but you have to set the path every time when you run your program . like this,

C:\Java\jdk1.5.0\bin\javac File_name.java
So instead of writing full path every time while running your program, its better to set the PATH for the java compiler and interpreter so that u will not have to write it again and again while running your java program.
What is the need of setting CLASSPATH ?


Like PATH environment variable it is also a predefined system variable in window OS. By setting CLASSPATH it indicates that users class file are present on that path and then user are eligible to run their .class file from any where through command prompt. 
But it is not recommended to set  CLASSPATH because in future user may wants to keep their .class file in other location , now that time again we need to change our CLASSAPTH. So it would be best to set CLASSPATH manually while running the program. For this all we need to do is ---



set CLASSPATH=path_name; 
How to set the  PATH in Java ?
Setting the path in Java means specifically we are going to set the path for the java compiler known as javac and java interpreter known as java. Unless we set the path we can't be able to run and interpret the java program or we can use java compiler by setting it while running the program but it is tedious as i mentioned above in " What is the need of setting path? " section . 


Now i am going to show you how to set the path in java through some snapshots so that it will be easy for you understand. Here we follow step by step . Its a very easy task and matter of only few minutes and you are done !


 Step 1 > Install the Java which is available in different versions like java 4, java 5, java 6 ,java 7 .But it is recommended to install java 5 because many new concepts are introduced from java 5, which you will fail to operate through java 4. 

It will be best to install JDK 5 from its official website . Here is the Link just have a click on it Click here for all version of JDK .

After installing Java a folder named Java is being created in program files , where you will find two folders names JDK < version_name> and JRE 

 Step 2 > After installing we need to copy the path of a bin folder created where all the executable files of java are present , have to post it to the PATH environment variable.

Here are the snapshots for copying the path for Java compiler. Follow each snapshots and then you are done with copying the path !

a) Select C:\ which is your system drive 
Select C:\ which is your system drive


b) Select the Program file folder 
Select the Program file folder


c) Now select Java Folder 

Now select Java Folder

D) After Clicking on Java folder you can see two folder one is JDK and another one is JRE Then you have to select JDK folder and open it by double clicking.
Select the JDK folder with version which you want
E) After clicking you can see that there is bin folder which is your required folder , now select this folder !
Select the bin folder
E) After clicking on bin a window will open all you need to click on the path bar and copy the path !
Java compiler and interpreter

Now here in this last snapshot you can see that there is a executable file named as javac which is known as Java Compiler . It is only responsible for compiling the java programs. 
Now here there is another executable file named as java just above the javac which is known as java interpreter and is work as an interpreter which is a task of JVM( Java Virtual Machine ) . 

So after copying the following path we need to paste it to the actual place where we set the PATH variable .



For setting up PATH variable see the following snapshots.  


A) Right click on Computer and select the properties option .




properties of System
B) This window appear after clicking on Properties option and now click on the Advanced Setting option
( on the left panel of the window)
Advanced System settings
C) Here select the Environmental Variables Button .
Environment variable
D) Here in the below image you can see there in no PATH variable available , there is nothing to worry just click on NEW button a window will open with two blank space available.
Note: If you have PATH variable then you just need to edit the path by clicking on EDIT option and paste the copied path to the variable value section by removing the previously written text on it and don't forget to terminate it with semicolon( ; ) . Unless you terminate with semi-colon it won't work. So be careful and make sure it must be terminated with semi-colon.
Setting path for java interpreter
E) Now You just need to write PATH in Variable name section and the path which you copied from bin folder need to paste it in variable value section and terminate it semi-colon as you see in the above image .Then click on OK button
Indicating path variable
F) After clicking on OK button in the above image the window appear will look like the below image that means you are successfully done. Now click on OK button and you are done with it !  How simple it was ! 
Saving path variable





Step 3 > Now to check whether you have successfully set the path or not just need to open the command prompt and simply write javac command. Now if java have been installed successfully and also path have been set then it show the following message after running the javac command.  
Checking java compiler working through command prompt

If its come like this then you are done setting path successfully. If it is not coming like this then you must have done some mistakes or you may missed out some point . So re-check the following steps. 

Now enjoy compiling and running  java programs !





Once the session is closed you can not be able to access the data from detached object and if you do you will get a LazyInitializationException: Session has been closed. It means that your session and session transaction is closed and you are trying to access the information from the proxy that is not initialized.
These are the solutions to overcome this LazyInitializationException :
  1. Open session in view.
  2. Thread local design pattern.
  3. Command design pattern.
  4. Long session
I will explain all of these in my next post but now we are going to talk about Open Session In View(OSIV).
To implement OSIV in your project you have to use filter that will open the session with every coming request and close the session after the JSP page is rendered to the client.

HibernateUtil

public class HibernateUtil {

    static SessionFactory factory;

    static {

        Configuration cfg=new Configuration();

        cfg=cfg.configure();

        factory=cfg.buildSessionFactory();

    }

    public static SessionFactory getSessionFactory() {

        System.out.println("factory: "+factory);

        return factory;

    }

}


In the above hibernateutil class you have static SessionFactory instance that will be initialized at the time of starting the server. So after starting the server you have an initialized instance of SessionFactory and you can get the object by using getter of this.

HFilter

public class HFilter implements Filter {

 private SessionFactory sf;
 @Override
 public void doFilter(ServletRequest hreq, ServletResponse hres,
   FilterChain chain) throws IOException, ServletException {
  // TODO Auto-generated method stub
  try {
   sf.getCurrentSession().beginTransaction();
   chain.doFilter(hreq, hres);
   sf.getCurrentSession().getTransaction().commit();
  }
  catch(Exception e) {
   e.printStackTrace();
  }
 }

 @Override
 public void init(FilterConfig fc) throws ServletException {
  // TODO Auto-generated method stub
  sf=HibernateUtil.getSessionFactory();
 }

 @Override
 public void destroy() {
  // TODO Auto-generated method stub
  
 }
}


Above you can see the servlet filter code that is responsible for managing the session. It will open the session on every incoming request and close the session after rendering the presentation page.
In the above code you can see that i used
sf.getCurrentSession().beginTransaction();

Here i didn't try to open and close the session i just used getCurrentSession() and begin the transaction on the session so you may question that who is responsible for opening and closing the session. Actually if you call getCurrentSession() then no need to open the session it will be initialized when you begin the transaction and closed when you commit the transaction.
So best of luck guy's.
Today i am going to tell you what are the Hibernate Fetching Strategies and how to use that in order to tune the performance of your applications.

So these are the fetching strategies in hibernate :
  1. join fetching(fetch="join") : In this case Hibernate will retrieves all the information in a single select statement.

  2. select fetching(fetch="select") : Here the Hibernate will pass the second select statement for fetching the associated collection unless you disable lazy fetching by specifying lazy="false".

  3. subselect fetching(fetch="subselect") : Here in this case the collection will be fetched using subselect sql statement unless you explicitly disable lazy fetching using lazy="false";

  4. batch fetching(batch-size="") : As the name suggest if you want to customize the number of select statement you can use batch fetching. It can be configured on both class and collection label.

  5. immediate fetching(lazy="false") ; Hibernate will load all the associated child collection with the parent.

  6. lazy collection fetching(lazy="true") :  here the associated collection will be loaded only when you use it or you can perform any operation on it(one of the best practice to tune the performance of your application).

  7. extra lazy : specific element of the collection is accessed as needed. Here in this case hibernate will not load the whole collection unless you tried. It is suitable for large collection.

proxy fetching, No-proxy, Lazy attribute fetching these 3 are also the fetching strategies that is rarely used. Mostly these three are used in lazy applications.
N+1 is one of the most famous question among java developers. It will give some performance issue if you where working on a large project. So it's better to resolve it using some below techniques.

What is n+1 problem ?

Ans: I am taking one example to let you understand that what n+1 problem is.
Suppose you have number of students in a college and every students have some number of books.
so one to many relation is between student and books.
Now suppose that you have to iterate through the collection of student and display all the books name he have. So the query will looks like this

"select * from Students"

"select * from Books where studentId=?"

Here you have 1 select statement for the student and if you have n number of students you have to fire n more query to select the books. So at the last you have to put n+1 select statement in order to perform this operation.

Now the next question is how to solve it ?

Using join fetching(it will join the parent and children and fetch all the information in a single statement) we can able to solve n+1 problem.
Now our next query will look like this

"from Students s join fetch s.Books b"


Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic