Liferay Popup’s

When developing a portlet in liferay sometimes there will be need to display content, page or even a portlet in popups. Liferay provides its inbuilt methods to have the facility of popups. In this article I will explain you the same and some other ways to use popups using Jquery and Ajax in liferay.

 Liferay Popup using Ajax + Alloy

In 6.1, Liferay uses pop-ups extensively. Here is the code you can simply put in your jsp to load a portlet or any other content asynchronously (Ajax) using Alloy. This will open an iFrame inside the alloy:

<aui:script>
               Liferay.provide(window,'showSiteManagement',function() {
                      var instance = this;
                      var url='<%= themeDisplay.getURLManageSiteMemberships().toString() %>';
                          Liferay.Util.openWindow(
                          {
                            cache: false,
                             dialog: {
                            align: Liferay.Util.Window.ALIGN_CENTER,
                             after: {
                            render: function(event) {
                            this.set('y', this.get('y') + 50);
                                     }
                                      },
                             width: 820
                           },
                           dialogIframe: {
                             id: 'siteManagementIframe',
                             uri: url
                                         },
                             title: 'Site Management',
                             uri: url
                             }
                             );
                             },
                             ['liferay-util-window']
               );
</aui:script>

I have used the “themeDisplay.getURLManageSiteMemberships().toString()” to get the URL to the portlet. However this below code can be used to render a JSP page:


<portlet:renderURL var="somePageURL" windowState="<%=LiferayWindowState.POP_UP.toString() %>">
               <portlet:param name="jspPage" value="/jsp/some/page.jsp"/>
               <portlet:param name="redirect" value="<%= currentURL %>"/>
</portlet:renderURL>
 

Using the popup without Alloy
Add the below code in your controller:

<portlet:renderURL var="somePageURL" windowState="<%= LiferayWindowState.EXCLUSIVE.toString() %>">

<portlet:param name="jspPage" value="/jsp/some/page.jsp"/>

<portlet:param name="redirect" value="<%= currentURL %>"/>

</portlet:renderURL>

Add the below script in your jsp page

<script type="text/javascript">

function showPopup() {

AUI().use('aui-dialog', 'aui-io', 'event', 'event-custom', function(A) {

var dialog = new A.Dialog({

title: 'Popup Title',

centered: true,

draggable: true,

modal: true

}).plug(A.Plugin.IO, {uri: '<%= somePageURL %>'}).render();

dialog.show();

});

}
 

Liferay popup using Jquery

Follow the below steps to integrate jquery with liferay:
1. Add the following content into your jsp page  

 <portlet:resourceURL var="resourceURL">
 </portlet:resourceURL>
 <table>
 ...
 <input id="popup" type="button" value="Popup"/>
 <script type="text/javascript">
 var $dialog;
 function <portlet:namespace/>showDialog(html, status,request)
 {
 $dialog.dialog('open');
 $dialog.html(html)
 return false;
 }
 $(document).ready(function() {
 $dialog = $('<div></div>').dialog({
 autoOpen: false,
 title: 'Export Dialog'
 });
 $('#popup').click(function()
 {
 jQuery.ajax(
 {
 url : '<%=resourceURL%>',
 dataType : 'String',
 success : <portlet:namespace/>showDialog,
 data : '<portlet:namespace/>',
 type : 'post'
 }
 );
 }
 );
 });
 </script>  

2.Call serveResource on Backing Portlet using Spring MVC Controller

 @Controller
 public class PopupController {
 ......
 @ResourceMapping
 public String renderResource(@RequestParam(value = "action") String action,
 @RequestParam(value = "refresh", required = false) boolean refresh, ResourceRequest request) throws PortletException,
 IOException {
return "popupJspName";
}

3.Supporting xml files

A.portlet.xml

 <portlet>
 <portlet-name>PopupPortlet</portlet-name>
 <portlet-class>org.springframework.web.portlet.DispatcherPortlet</portlet-class>
 <init-param>
 <name>contextConfigLocation</name>
 <value>/WEB-INF/context/popup-portlet.xml</value>
 </init-param>
</portlet> 

B. popup-portlet.xml

 <bean id="popupController"/>
<bean id="portletModeHandlerMapping" class="org.springframework.web.portlet.handler.PortletModeHandlerMapping">
 <property name="defaultHandler" ref="popupController"/>
      <property name="portletModeMap">
<map>
<entry key="view">
<ref bean="popupController"/>
</entry>
         </map>
    </property>
</bean>  

We are done….. Enjoy using popups with liferay. 🙂

Solve ECJ error in liferay IDE

You must have come across the errorTask cannot continue because ECJ is not installed. ECJ was automatically installed. Please rerun your task. Total time: 6 secondwhile ant running the build.xml file in liferay.

To solve this error follow the below steps:

In eclipse Go to Window (menu) –> Preferences and the below window gets opened up:2012-12-29_150309

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Where you can see an option named “Ant”. Under the Ant option select runtime, so you will see the above showed Runtime tab.

Select the Global Entries section, now on the right hand side click on the Add External Jar. Select the ecj.jar file kept in your computer.

You can find the ecj.jar in the liferay sdk/lib folder. And that’s it. Now build your project again. You will see a BUILD SUCCESSFFULL message.

Cheers!!!

Concept of Heap Size In Java (OUT OF MEMORY ERROR)

Have you ever came across the error like java.lang.OutOfMemoryError in Tomcat, while running an application???? Then this the r8 place you are wondering for.

You generally get along with this error, when you are trying to access extra memory for objects, than the actually defined fixed size. The size allocated when creating new objects is called as heap size.

HEAP SIZE:  When you are working with any application in java, a specific memory is allocated to Java virtual machine (JVM) by Operating System. JVM uses this memory for all its work and from this , a part of memory is known as JAVA HEAP MEMORY.

When any object is created by new operator or by some other way, it is allocated some memory space from heap. If the object creation requires more space than the heap size it throws the error java.lang.OutOfMemory. Heap resides at the bottom space of the memory allocated to JVM.

Java Heap space is generally divided into three regions or generation for sake of garbage collection

i) New Generation

ii) Old or tenured Generation

iii) Perm Space (permanent Generation).

As and when the object dies or is garbage collected , the free memory is joined to the heap memory. The default heap size limit in java is 128MB for a 32-bit, but it highly varies from JVM to JVM. But this is not it, you can also change the heap space if required when you need more objects or your application is quite large.

Changing the heap size

Generally there are two functions that deal with changing the heap size:

1) -Xms : This signifies the minimum(initial) heap size in java.

2) -Xmx : This signifies the maximum heap size in java.

To change the heap size , open CMD-> Change the directory to path where your java is installted.

Suppose your java is installed in directory C:\Program Files (x86)\Java\jdk1.7.0-64\bin

Below shown screen shot shows you the wayto change heap size:

cmd

 

 

Press enter and your heap size gets changed to minimum size of 256Mb and maximum size of 1024Mb.

Program to know heap size:


public class Heapsize {

public static void main(String [] args) {

int mb = 1024*1024;

//Getting the runtime reference from system

Runtime runtime = Runtime.getRuntime();

System.out.println ("##### Heap utilization statistics [MB] #####");

//Print used memory

System.out.println("Utilized Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / mb);

//Print free memory

System.out.println ("Free Memory:" + runtime.freeMemory() / mb);

//Print total available memory

System.out.println ("Total Memory:" + runtime.totalMemory() / mb);

//Print Maximum available memory

System.out.println ("Maximum Memory:" + runtime.maxMemory() / mb);

}

}

Output:

output

Java also provides you the facility to change the Thread stack size by the function:

i)   -Xss<size>  set java thread stack size

Hope this helps you. If you face any problem in this blog do leave a message, always keen to help you… 🙂

Encryption and Decryption using AES algorithm in java

In Today’s Internet Era it is highly recommended to keep your data utmost secure from threa12ts and attacks. Attacks are highly costly, whether the attack comes from inside or out. As computer (and especially Internet) technologies evolve, security attacks are becoming more sophisticated and frequent. We have to stay updated with the latest techniques and tools for our Application safety and security, and for this the solid foundation in various technologies such as data encryption, authentication, and authorization is a necessity.

In our web application many things need to get secured , take for an example in  online banking and shopping, recorded data is stored in many places, including bank accounts, store accounts, and medical accounts. User Password, telephone no, credit card no’s, bank account no, etc. are vulnerable to attacks, so these data needs to be highly secured.

So, in this article I will explain you how to secure your data by encrypting and decrypting of data using AES algorithm in java:

Now for encrypting the data, we must use a secret key, which will only be provided to the sender and the receiver using which they can encrypt and decrypt the data. In our example we use an algorithm called AES 128 and the bytes of the word “ThisIsASecretKey” as the secret key. AES algorithm can use a key of 128 bits (16 bytes * 8); so we have selected that key.

Before moving to the example let me make you familiar with some basic terms:

1)      Key Generator class: This provides the methods for cryptographic operations. KeyGenerator objects are reusable, i.e., after a key has been generated, the same KeyGenerator object can be re-used to generate further keys. This class is imported as javax.crypto.KeyGenerator.

2)      generateKey (): This is a static method of the Key Generator class, which is used to generate a secret key using a key for an AES algorithm.

3)      Cipher class: This class provides the cryptographic cipher for encryption and decryption of data. This class forms the base for the Java Cryptographic Extension (JCE) framework. This class is imported as javax.crypto.Cipher.

To create a cipher object, the application calls the Cipher’s getInstancemethod, and passes the name of the requested transformation to it.

A transformation is a string that describes the operation to be performed on the given input, to produce some output. A transformation always includes the name of a cryptographic algorithm (e.g., AES), and may be followed by a feedback mode and padding scheme.

A transformation is of the form:

  • algorithm/mode/padding” or
  • algorithm

For example the correct transformation could be:

 Cipher cipher = Cipher.getInstance("AES/OFB32/PKCS5Padding");

As we are clear with the main concepts, let’s look at the example:

The AES algorithm:


package com.demo.crypto;

import java.security.*;

import java.security.spec.InvalidKeySpecException;

import javax.crypto.Cipher;

import javax.crypto.spec.SecretKeySpec;

import sun.misc.*;

public class Cryptoalgo {

private static final String ALGORITHM = "AES";

private static final byte[] keyValue =

new byte[] { 'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y' };

public static String encrypt(String valueToEnc) throws Exception

{

Key key = generateKey();

//Get the instance for AES algorithm

Cipher c = Cipher.getInstance(ALGORITHM);

c.init(Cipher.ENCRYPT_MODE, key);

byte[] encValue = c.doFinal(valueToEnc.getBytes());

String encryptedValue = new BASE64Encoder().encode(encValue);

return encryptedValue;

}

public static String decrypt(String encryptedValue) throws Exception

{

Key key = generateKey();

//Get the instance for AES algorithm

Cipher c = Cipher.getInstance(ALGORITHM);

c.init(Cipher.DECRYPT_MODE, key);

byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedValue);

byte[] decValue = c.doFinal(decordedValue);

String decryptedValue = new String(decValue);

return decryptedValue;

}

private static Key generateKey() throws Exception

{

Key key = new SecretKeySpec(keyValue, ALGORITHM);

//Below Shown is the code for key generation for DES algorithm

// SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);

// key = keyFactory.generateSecret(new DESKeySpec(keyValue));

return key;

}

}

Below shows the code to utilize the above AES algorithm:

package org.demo.crypto;

public class TestExample {

public static void main(String[] args) throws Exception {

String password = "secretpassword";

String passwordEnc = Cryptoalgo.encrypt(password);

String passwordDec = Cryptoalgo.decrypt(passwordEnc);

System.out.println("Plain Text : " + password);

System.out.println("Encrypted Password : " + passwordEnc);

System.out.println("Decrypted Password: " + passwordDec);

}

}

On running the above program you will have the output as:

Plain Text: secretpassword

Encrypted Password: U2FsdGVkX18gnSxz3QREK1HIwIphACMt5JBeQhSwf3w=

Decrypted Password: secretpassword

Hope you have a secure stuff in your application on web 🙂

Calling a C program from java

Java provides us with a native interface which allows calling native programs (code) like C, C++, etc. and this interface is called as Java Native Interface (JNI).

Java Native Interface(JNI): The Java SDK’s Java Native Interface (JNI) is a programming framework that enables Java code running in a Java Virtual Machine (JVM) to call, and to be calledby, native applications (programs specific to a hardware and operating system platform) and libraries written in other languages such as C, C++ and assembly.

At compile time, JNI defines how Java data types correspond to C data types. C programs get this

Information from JNI header files that come with the Java SDK.

The header files for specific application/program are created using a tool named Javah.

Javah: A tool that comes with the SDK, creates application-specific header files that helps to eliminate programming errors in communication between Java and C routines.

At run time, JNI lets Java objects be passed to C code, and lets C code access Java properties and methods. Thus, C code can set properties of Java classes, making it possible to call Java methods from C and vice versa.

image

JNI acts as an intermediate between Java Code and  other native languages, this calling of native code can be used to avoid the rewriting the code in java, and implements the functionality of code reusability.

Some simple steps to call a c method from java program:

Step-1: Create a Java program that contains the declaration of the C methods as native. 

Step-2: Compile the java program. 

Step-3: Use the Javah tool to create a header file that corresponds to the Java program.          

Step-4: Write the C code and compile the program.                                    

Step-5: Generate the shared library.                

Step-6: Execute the Java program.

 

Step-1: Creating a java program with declaration of C methods as native

In our example we will take a simple example with a welcometoC() method which is a native method of C to be called from java program.

The code to call the native method is:

public native void welcometoC(); 

The above declaration instructs the Java compiler that the program calls a native method. This declaration enables the integration of a C method (welcometoC) within a Java program.

After the native method is declared, you need to load the library that contains the implementation of the method you are going to call in the Java code. The following statement loads the library:

static {
System.loadLibrary("DemoC");
} 

So the complete java program is:-

//Demo.java
public class Demo {

// Declaration of the native method

public native void welcometoC();

/*The native keyword tells the compiler that the implementation of this method is in a native language*/
/*Loading the library containing the implementation of the native method*/

    static {
      	  System.loadLibrary("DemoC");
               }
//invoking the native method
    public static void main(String[] args)
   {
        new Demo().welcometoC();
    }
}

Step-2: Compile the java program   Compile the java program with javac compiler. During compilation, the compiler includes information about the native methods declared in the code. This helps to develop the header file.


 Step-3: Use the Javah tool to create a header file that corresponds to the Java program                   

For creating the header files use the Javah tool, which is available in the JDK in the Bin folder.

Do place the header file in the include directory in the JDK folder, as this file provides the signature of the native method declared in the java program.

The header file provides the following signature:

Java_Demo_welcometoC(JNIEnv*, jobject);

  • JNIEnv*: Represents an interface pointer.
  • jobject: Signifies a reference to the Java object for which the native method is invoked.

The JNIEnv* is the pointer to the thread that invokes a native method. This pointer is used by the C implementation code to access objects or variables from the Java code.

The header file is generated as shown below:

//Demo.h

/* DO NOT EDIT THIS FILE - it is machine generated */

#include <jni.h>

/* Header for class Demo */

#ifndef _Included_Demo

#define _Included_Demo

#ifdef __cplusplus

extern "C"

{

#endif

/*

* Class:     Demo

* Method:    welcometoC

* Signature: ()V

*/

JNIEXPORT void JNICALL Java_Demo_welcometoC (JNIEnv *, jobject);

#ifdef __cplusplus

}

#endif

#endif

//end of Demo.h

Step-4: Write the C code and compile the program

// DemoC.c

#include <stdio.h>

#include <jni.h>

#include "Demo.h"

//definition of methodOfC()

&nbsp;

JNIEXPORT void JNICALL Java_Demo_welcometoC (JNIEnv *env, jobject javaobj)

{

printf("Hello this is C program\n");

printf("Going back to Java program…");

return;

}

In the above C program some terms to get known are:

  • jni.h: Provides the interface between Java and C.
  • Demo.h: Represents the header file generated from Demo.class.
  • stdio.h: Represents a standard library C header file needed for printf().

Now to compile the c program we need the c compiler, so I have used the Tiny C. Download and unzip the file and set the OS path to tcc.exe

Step-5: Generate the shared library

To generate the shared library file dll use the following command:

tcc DemoC.C -I C:/Progra~1/Java/jdk1.7.0_07/include -I C:/Progra~1/Java/jdk1.7.0_07/include/win32 -shared -o Demo.dll

Two directories are included in the compile command, those are to include the jni.h and jni_md.h

Step-6: Execute the Java program

As we are done with all the compilations, run the java program with specific java tool.

OUTPUT:                           

Hello this is C program

Going back to Java program…

Your Queries are always welcomed 🙂

Running scripting language in Java

Last week while I was working on an application which needed the maximum use of Scripting language, a thing just stroked in my mind, can’t we run scripts directly in different languages????

On lot of searching, I just came up with the solution of using scripting language like JavaScript, python, NetRexx, TCL etc. within the java language with utmost ease.

Java 6 introduces scripting engine support in to Java, and this new support provides a link between the Java and delayed binding world of scripting languages.

This all is possible with a simple package that java provides us. The Java Scripting functionality is in the javax.script package. This is a relatively small, simple API. Scripts can be executed from within java in the JVM. Many independent scripting packages have been available for Java for some time, including Rhino, Jacl, Jython, BeanShell, JRuby, and others. To work with scripts, you only need to know a couple of key classes, form which here we will learn two of them:

1)     ScriptEngineManager

2)     ScriptEngine

The ScriptEngine interface models script engines, and the ScriptEngineManager class provides convenient methods to register and obtain a ScriptEngine object.

ScriptEngineManager:

To instantiate a script engine, you use the ScriptEngineManagerclass to retrieve a ScriptEngine object for the scripting language you’re interested in. Each scripting language has a name like JavaScript, rhino etc.

Generally it handles two key functions:

i.            Discovery of script engine

ii.            Storing data in context

It provides a key value pair, which is provided to all the instances of ScriptEngine created by the ScriptEngineManager and it is referred as “Global state”.

ScriptEngine:

ScriptEngine is an interface which handles script interpreting and evaluation. This is implemented separately for every single language. Apache commons provides a project Jakarta Bean Scripting Framework (BSF) which gives implementation for a several set of scripting languages like TCL, NetRexx, JavaScript, Python lot more…

Let’s take an example using JavaScript as a scripting language:

import javax.script.ScriptEngine;

import javax.script.ScriptEngineManager;

import javax.script.ScriptException;

public class ScriptDemo {

public static void main(String[] args) {

// create a ScriptEngineManager object

ScriptEngineManager manager = new ScriptEngineManager();

// get the ScriptEngine instance

ScriptEngine engine = manager.getEngineByName("javascript");

// execute script

String script = "print('This is an example to run JavaScript in java')";

try {

engine.eval(script);

engine.eval("var a= 10;");

engine.eval("var b = 10;");

engine.eval("var c = a + b;");

engine.eval("print (c);");

} catch (ScriptException e) {

e.printStackTrace();

}

}

}

The output of the program will be:

 

 

 

 

 

For more information on scripting packages, its variables, API and various examples to work with you can visit Java Scripting guide.

So if you find a problem like mine and hopefully you come across this article, I would be grateful helping you with your queries 🙂

Learning a simple hibernate program

Here I will explain Hibernate sample program using Java Application in Eclipse IDE. In this example we will insert record in MySQL database.

Follow the instructions step by step to run your Simple Hibernate Program in Eclipse IDE

Step – 1 Creating Java Project

Step – 2 Project Structure For Hibernate Example

Step – 3 Create hibernate.cfg.xml(Configuration file)

Step – 4 Create a Pojo File(mapping to database table)

Step – 5 Creatingusercontact.hbm.xml

Step – 6 Create The Class To Insert Records

Step – 7 Adding Jar Files

Step – 8 Run Your Main Class File

Step- 1 Creating Java Project

Start Eclipse and go to File -> New -> Project -> Java Project

On clicking next you will have to enter the Project name and your project gets created.

Step- 2 Project structure for Hibernate example

– The project structure for Hibernate_Example is shown below:

Step- 3 Create hibernate.cfg.xml (Configuration file)

-hibernate.cfg.xml:

<property  name=”hibernate.connection.driver_class”>com.mysql.jdbc.Driver</property>

The above shown is the property is for loading the Drivers in MySQL database.

<property name=”hibernate.connection.url”>jdbc:mysql://localhost/usercontact</property>

The above property is used to open connection to database named usercontact which runs in localhost.

<property name=”hibernate.connection.username”>root</property>

The above property shows that the username for the database connection is root.

<property name=” hibernate .connection. password”> </property>

The above property shows that there is no password used for the database connection.

<property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>

The dialect property  is org.hibernate.dialect.MySQLDialect which tells the Hibernate that we are using MySQL Database.

Hibernate supports many databases for Object/Relational Mapping and Transparent Object Persistence for Java. We can use following databases dialect type property:

<mapping resource=”usercontact.hbm.xml”/>

The above property is used for mapping  usercontact table.


<?xml version=<em>'1.0'</em> encoding=<em>'utf-8'</em>?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<property name=<em>"hibernate.connection.driver_class"</em>>com.mysql.jdbc.Driver</property>

<property name=<em>"hibernate.connection.url"</em>>jdbc:mysql://<span style="text-decoration: underline;">localhost</span>/<span style="text-decoration: underline;">usercontact</span></property>

<property name=<em>"hibernate.connection.username"</em>>root</property>

<property name=<em>"hibernate.connection.password"</em>></property>

<property name=<em>"hibernate.connection.pool_size"</em>>10</property>

<property name=<em>"show_sql"</em>>true</property>

<property name=<em>"dialect"</em>>org.hibernate.dialect.MySQLDialect</property>

<property name=<em>"hibernate.hbm2ddl.auto"</em>>update</property>

<!-- Mapping files -->

<mapping resource=<em>"usercontact.hbm.xml"</em>/>

</session-factory>

</hibernate-configuration>

Step- 4 Create a pojo file (mapping to database table)

Hibernate uses the Plain Old Java Objects (POJOs) classes to map to the database table. We can configure the variables to map to the database column. Here is the code for usercontact.java:


package com.demojava;

public class usercontactVO {

private String firstName;

private String lastName;

private int phone;

private String email;

private long 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;

}

public int getPhone() {

return phone;

}

public void setPhone(int phone) {

this.phone = phone;

}

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;

}

public long getId() {

return id;

}

public void setId(long id) {

this.id = id;

}

}

Step- 5 Creating usercontact.hbm.xml

This file is used to map the usercontact object to usercontact table in database. Here is the code for usercontact.hbm.xml:


<?xml version=<em>"1.0"</em> encoding=<em>"UTF-8"</em>?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name=<em>"com.demojava.usercontactVO"</em> table=<em>"usercontact"</em>>

<id name=<em>"id"</em> type=<em>"long"</em> column=<em>"ID"</em> >

<generator class=<em>"assigned"</em>/>

</id>

<property name=<em>"firstName"</em>>

<column name=<em>"FIRSTNAME"</em> />

</property>

<property name=<em>"lastName"</em>>

<column name=<em>"LASTNAME"</em>/>

</property>

<property name=<em>"email"</em>>

<column name=<em>"EMAIL"</em>/>

</property>

<property name=<em>"phone"</em> type=<em>"int"</em>>

<column name=<em>"PHONE"</em>/>

</property>

</class>

</hibernate-mapping>

Step- 6 Creating the class to insert records.

Before creating a class we should be clear about hibernate session.

Hibernate session: Hibernate Session is the main runtime interface between a Java application and Hibernate. SessionFactory allows applications to create hibernate session by reading hibernate configurations file hibernate.cfg.xml.

On session.save(contact) will save the information into database.


package com.demojava;

import org.hibernate.Session;

import org.hibernate.Transaction;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class main1

{

public static void main (String[] args) {

Session session = null;

try{

// This step will read hibernate.cfg.xml and prepare hibernate for use

SessionFactory sessionFactory = new

Configuration().configure().buildSessionFactory();

session =sessionFactory.openSession();

Transaction tx=(Transaction)session.beginTransaction(); // Add this soon after initializing session object

//Create new instance of usercontactVO and set values in it by reading them from form object

System.out.println("Inserting Record");

usercontactVO contact = new usercontactVO();

contact.setId(1);

contact.setFirstName("Indies");

contact.setLastName("Services");

contact.setEmail("indies.co.in");

contact.setPhone(12345);

session.save(contact);

tx.commit();

System.out.println("Done");

}

catch(Exception e){

System.out.println(e.getMessage());

}

finally {

// Actual contact insertion will happen at this step

session.flush();

session.close();

}

}

}

Step- 7 Adding jar files

The following jar files needs to be added to run the application/Example in Hibernate

You can add jar files as shown below:

Click on project on right click select properties which will open the following Dialog box.

Step- 8 Run your Main Class Files

Right click  project -> Run As -> Java Application

This is the output you will find- And you records get inserted.

Hope this helps you 🙂 Your queries are always welcomed…