Sunday, June 10, 2012

Java Decompiler (Jad) : A Smart guide

Jad is a command line Java decompiler written by Pavel Kouznetsov,written for several plateform.
can be downloaded from
1. http://www.kpdus.com/jad.html
2. http://www.varaneckas.com/jad

Installation is very easy,just extract the downloaded zip .
Set the environment variable path for your plateform here I am using windows.
After setting the path variable open the cmd to check the proper installation type jad on
command prompt,if every thing goes fine you will find the fallowing outupt.








To decompile single java class use the command
jad -sjava MyClass.class

To decompile Multiple java class use the command
jad -o -r -sjava -dsrc bin/**/*.class

Jadclipse plugin for Eclipse
Download the Jadclipse for eclipse from http://sourceforge.net/projects/jadclipse/
Copy the extracted jars in the Eclipse plugin folder.
Restart the Eclipse and set the decompliler path as shown









Now your Eclipse is ready to decompile any java class whose source file is not provided with you,just press
F3 on the name of the class and see the magic.

Ant Build File to decompile all the classes inside the jar

<project name="Decompile_jars" default="main" basedir=".">


<taskdef resource="net/sf/antcontrib/antcontrib.properties"/>


<property name="jad" location="c:/program files/jad1.5.8/jad.exe"/>
<property name="unjar.dir" location="loc_unjar"/>

<target name="main">
    <input
        message="Please enter jar file name"
        addproperty="input.file"
        defaultvalue="source"
    />

    <!-- clean temp dir -->
    <delete dir="${unjar.dir}"/>

    <!-- unpack jar file -->    
    <unjar src="${input.file}.jar" dest="${unjar.dir}"/>

    <!-- decompile all class files -->
    <exec executable="cmd.exe">
        <arg line="/c ${jad} -o -r -sjava -d${unjar.dir} ${unjar.dir}/**/*.class"/>
    </exec>     
     
    <!-- create jar file -->
    <jar destfile="${input.file}_decompile.jar">
        <fileset dir="${unjar.dir}"
            excludes="**/*.class"
        />
    </jar>

    <!-- clean temp dir -->
    <delete dir="${unjar.dir}"/>
    
</target>


</project>

Spring Framework and SL4J Integration

The Simple Logging Facade for Java or (SLF4J) serves as a simple facade or abstraction for various logging frameworks, e.g. java.util.logging, log4j and logback, allowing the end user to plug in the desired logging framework at deployment time.

slf4j is actually not a logging library - it's just a facade. You choose a logging framework by yourself. We use slf4j and logback that implements the slf4j API natively.

The SLF4J project has similar goals to commons-logging. It uses quite a different approach, however, which has both benefits and drawbacks. Future versions of commons-logging may adopt some of the concepts of SLF4J.

Spring uses Jakarta Common Library(JCL) and java.util.logging,SL4J has advantages over JCL as it does not suffer
from class loader problem and Memory Leak Problem.SLFJ for logging in java use parametrized version of various log methods they are faster as compared to normal method.


Lests Demonstrate the Integration of SL4J to String framework,in this example we are using SL4J with logback framework

Step 1: Create Java Project.
Step 2: Add Spring Library,SL4J jars and Logback jars in build path as shown





Step 3: Create a class which includes logger as fallows
package com.main;



import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloSl4j {
 
 private static final Logger logger = LoggerFactory.getLogger(HelloSl4j.class);
 
 public void sayHello(){
  logger.info("Inside the sayHello Method");
  System.out.println("Say Hello To Spring SL4J Integration");
 }
}




Step 4: create the spring.xml for your application context as shown


 

 



Step 5: create your logger.xml to configure logging as fallows
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
 
 <appender name="STDOUT"
            class="ch.qos.logback.core.ConsoleAppender">
 
    <!-- encoders are assigned by default the type
         ch.qos.logback.classic.encoder.PatternLayoutEncoder -->
    <encoder>
   <pattern>
    %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
   </pattern>
    </encoder>
  </appender>
 
 <root level="INFO">
  <appender-ref ref="STDOUT" />
 </root>
 
</configuration>

Step 6: Create your main class fallows

package com.test;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.main.HelloSl4j;

public class HelloSl4jTest {

 public static void main(String[] args) {
  ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
  HelloSl4j helloSl4j = (HelloSl4j) ctx.getBean("helloSl4j");
  helloSl4j.sayHello();
 }

}


Here is the Logging Console





Saturday, June 9, 2012

Working with Java SE 7 Exception Changes

Working with Java SE 7 Exception Changes

Jelastic : A better Cloud Hosting Solution for Java

Lets try Jelastic Cloud hosting solution which is far better and easier solution than Google App Engine.
The other cloud hosting Solution which are getting popular these days are Cloud Foundry and OpenShift.
i am not going to compare all these hosting solution but try to getting started with Jelastic which
offer a very user friendly UI to setup your application environment.
I am trying to setup my small application on the Jelastic platform its not that tough as I was thinking it
the http://jelastic.com/ home page is self explanatory how you should start from.

lets setup our application environment by selecting JDK 6,Tomcat 6 and MongoDB as our NoSQL database,choose
your hosting provide and signup for free








Login with the password sent by jelastic to your registered mail address
provide enviornment name and press create









After pressing the create button jelastic takes some time to configure your enviornment and send the MongoDB
node details to your registered mail id open the RockMongo (MongoDB web UI) with the help of provided userid and password.

Setup MongoDB configuration like database name,collection name etc with the help of GUI.








After Deploying the application Test you application on http://testap.jelastic.servint.net/view/index.jsp
And MyApp is up and Running








Spring : Working with JdbcTemplates

Spring provides JDBC Templates to access the data from the database with ease.Spring provides
org.springframework.jdbc.core.JdbcTemplate which basically take cares about all your
connection establishment to the database post query work eg closingh statement and connections.

Merits of spring templates as compared to conventinal Data access through JDBC
1. Connection Handling is done by Spring container you need not to worry about it,by this way
it reduced the singnificant amount of the coding.
2. Exception handling in conventional data access through JDBC is very cumbersome process,
here Spring take care of all these stuff by converting SQLException to the RuntimeException
3.ResultSetExtractor or RowMapper which allows result directl into the Object ResultSetExtractor
or a list of objects RowMapper.

Lets have a walk through how to work with JdbcTemplates

Step 1: Create your database as fallows,Here I am using MySQL as database.




Step 2: Create the Java Project and add Spring framework jar library to it.
Step 3: Create spring.xml as shown



 
 
 
 
  
  
  
  
  
  
 
 




Step 4:
Create Employee Model Class as shown
package com.example.model;

public class Employee {
 
 private int empid;
 private String empName;
 
 public Employee(int empid,String empName){
  this.empid = empid;
  this.empName = empName;
 }
 
 public int getEmpid() {
  return empid;
 }
 public void setEmpid(int empid) {
  this.empid = empid;
 }
 public String getEmpName() {
  return empName;
 }
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 

}

Step 5:Create the Data Access Object as fallows
package com.example.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.example.model.Employee;
@Component
public class EmpDaoImpl {
 
 @Autowired
 private DataSource dataSource;
 
 public void create(int empid, String employee_name) {
  JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
  jdbcTemplate.update("INSERT INTO EMPLOYEE (empid, EMPLOYEE_NAME) VALUES(?,?)",
    new Object[] { empid, employee_name });
 }
 
 public DataSource getDataSource() {
  return dataSource;
 }

 public void setDataSource(DataSource dataSource) {
  this.dataSource = dataSource;
 }

}

Step 6: Create your main class as fallows to check whether all these things are in right shape.
package com.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.example.dao.EmpDaoImpl;
import com.example.model.Employee;

public class Main {
 
 public static void main(String[] args) {
  
  ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
  EmpDaoImpl empdl = ctx.getBean("empDaoImpl",EmpDaoImpl.class);
  
  empdl.create(1, "Sharad Singh");  
  
  System.out.println("Data Inserted In Database");
 }

}

Output @ console:
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Data Inserted In Database

Step 7:
Look into the database table whether data has been updated or not,Here you go......






Friday, June 8, 2012

Spring : Working with DataSource and Database Connection Pooling

Getting Database connection through conventional JDBC is very tedious task which include a lot
Exception handling and repeative coding,Spring simplifies the whole process with very ease.
Spring provides the org.springframework.jdbc-3.1.0.RELEASE.jar whic contains the org.springframework.jdbc.datasource.DriverManagerDataSource to get the connection
object to the Database.

For the production environment we can use org.apache.commons.dbcp to implement the connection
pooling,here I summarize how we implement the connection pooling in spring framework.
Step 1: The very first step is to create the Java project and add the Spring Library as fallows







Step 2:Setup the database,in this example i am using MySQL as a database,ensure MySQL database driver jar
should be in the class path.
Step 3:Crate the spring.xml file in source folder as fallows

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
  xmlns:context="http://www.springframework.org/schema/context">

 <context:annotation-config/>
 <context:component-scan base-package="com.example"/>
 
 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
  <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
  <property name="url" value="jdbc:mysql://localhost:3306/HibernateDb"/>
  <property name="username" value="root"/>
  <property name="password" value="root"/>
  <property name="initialSize" value="2"/>
  <property name="maxActive" value="5"/>
 </bean>
 

</beans>

Step 4: Create your Model Class as fallows
package com.example.model;

public class Employee {
 
 private int empid;
 private String empName;
 
 public Employee(int empid,String empName){
  this.empid = empid;
  this.empName = empName;
 }
 
 public int getEmpid() {
  return empid;
 }
 public void setEmpid(int empid) {
  this.empid = empid;
 }
 public String getEmpName() {
  return empName;
 }
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 

}

Step 5: create DataAccessor Object to get the data from database

package com.example.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.example.model.Employee;
@Component
public class EmpDaoImpl {
 
 @Autowired
 private DataSource dataSource;
 
 public Employee getEmployee(int empid) throws Exception{
  
  Connection conn = null;
  conn = dataSource.getConnection();
  PreparedStatement ps = conn.prepareStatement("select * from employee where empid = ?");
  ps.setInt(1, empid);
  
  Employee emp = null;
  ResultSet rs = ps.executeQuery();
  
  if(rs.next()){
   emp = new Employee(empid, rs.getString("employee_name"));
  }
  rs.close();
  ps.close();
  
  return emp;
  
  
  
 }

 public DataSource getDataSource() {
  return dataSource;
 }

 public void setDataSource(DataSource dataSource) {
  this.dataSource = dataSource;
 }

}

Step 6: Now test your prog by using your Main Class as shown

package com.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.example.dao.EmpDaoImpl;
import com.example.model.Employee;

public class Main {
 
 public static void main(String[] args) {
  
  ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
  EmpDaoImpl empdl = ctx.getBean("empDaoImpl",EmpDaoImpl.class);
  
  Employee emp = null;
  try {
   emp = empdl.getEmployee(1);
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  System.out.println(emp.getEmpName());
 }

}
Output






Thursday, June 7, 2012

Convert JSON to DBObject

Conversion of JSON to DBObject need JSON parsing only here I attach the simple
code to understand it.
package com.test;

import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;

public class ConvertJSON2DBObject {
 public static void main(String[] args) {
  try {
   Mongo mongo = new Mongo("localhost",27017);
   DB db = mongo.getDB("myDBName");
   DBCollection collection = db.getCollection("myCollectionName");
   
   //convert JSON to DBObject
   DBObject dbObject = (DBObject) JSON.parse("{'empName':'Rajkumar Singh','emppId':62990}");
   collection.insert(dbObject);
   
   DBCursor cursor = collection.find();
   
   while(cursor.hasNext()){
    System.out.println("OBJ IS : "+cursor.next());
   }
  } catch (UnknownHostException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (MongoException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
 }

}


Java MongoDB Tutorial

Working with MongoDB with java involves few steps
Step 1: include the java driver into the CLASSPATH
Step 2: start the mongodb service if installed
here is the demo code

package com.test;

import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class MongoHelloJava {

 public static void main(String[] args) {
  try {
   //Demonstrate simple hello java program with mongoDB
   
   System.out.println("Demonstarting simple insert and retrivel in MongoDB");
   // connect to mongoDB on default port and IP address
   Mongo mongo = new Mongo("localhost",27017);
   
   // getDB() return the database from MongoDB,
      //  mongoDB will create database automatically if not existed
   DB db = mongo.getDB("myMongoDB");
   
   // getCollection() returns the collection from MongoDB
   // mongoDB will create collection automatically if not existed
   DBCollection collection = db.getCollection("myCollection");
   
   // create a document to store key and value
   BasicDBObject document = new BasicDBObject();
   document.put("id", 1000);
   document.put("print", "hello  Java");
   
   // save it into collection named "myCollection"
   collection.insert(document);
   
   // query for searching perticular id
   BasicDBObject query = new BasicDBObject();
   query.put("id", 1000);
   
   // fire query
   DBCursor cursor = collection.find(query);
   
   // iterate through cursor
   while(cursor.hasNext()){
    System.out.println(cursor.next());
   }
   
   // Demonstrate getCollection() and getCollections()
   System.out.println("Demonstrate getCollection() and getCollections()");
   Set<String> collections = db.getCollectionNames();
    

   for (String collectionName : collections) {
   System.out.println(collectionName);
   }


   //get a particular collection
     DBCollection collection1 = db.getCollection("myCollection");
   System.out.println("Collection Name is : "+collection1.toString());
   
   //insert the data into the database
   BasicDBObject document1 = new BasicDBObject();
   document1.put("post", "rajkrrsingh.blogspot.com");
   document1.put("author", "Rajkumar Singh");
   
   BasicDBObject comments = new BasicDBObject();
   comments.put("user1", "text1");
   comments.put("user2", "text2");
   comments.put("user3", "text3");

   document.put("comment", comments);
   collection.insert(document1);
   System.out.println("document1 inserted succesfully");
   
   //insertion of the data into the database through map
   Map<String, Object> documentMap = new HashMap<String, Object>();
   documentMap.put("post", "rajkrrsingh.blogspot.com");
   documentMap.put("author", "Rajkumar Singh");
    
   Map<String, Object> commentMap = new HashMap<String, Object>();
   


   commentMap.put("user1", "text1");
   commentMap.put("user2", "text2");
   commentMap.put("user3", "text3");
    
   documentMap.put("comment", commentMap);
    
   collection.insert(new BasicDBObject(documentMap));
   
   DBCursor cursor1 = collection.find();
   while (cursor1.hasNext()) {
    System.out.println(cursor1.next());
   }
   
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (MongoException e) {
   e.printStackTrace();
  }

 }

}



Result




Wednesday, June 6, 2012

All About MangoDB


NoSql DB is one of the latest trends in the market which most of the big names in the industry are investing in and are getting benefited by its huge spectrum of features. The common feature associated with NoSQL are Storing huge Data & Scaling up Storage, Interconnected Data, Complex Data Structure, High performance and Flexibility with schema less approach.

Major Internet giants like Facebook, Twitter, Digg, Amazon, LinkedIn, craigslist, Foursquare and Google all use NoSQL in one way or another because of the significantly different challenges in dealing with huge quantities of data that the traditional RDBMS solutions could not cope with.


MongoDB (from "humongous") is a scalable, high-performance, open source, document based NoSQL database used by company like craigslist, Foursquare, Disney, MTV and many more.





Tuesday, June 5, 2012

MongoDB Tutorial : Getting Started

MongoDB is no SQL,open source database, written purely in C++, basically store the database in the document form.
based on the JSON approach,can be horizontally scalable,can be index on any attribute

Here are the best practise to use











How to download and Install MongoDB
Download the MongoDB from the MongoDB website as depicted in the picture as per your
plateform,here I am downloading it for the Windows 32 bits.











Download the relevent Driver to work for
The fallowing page shows the link for the driver,Here I am working with the Java Driver.








Review the downloaded bineries
After downloading MongoDB,extract the zip file which contains the fallowing exe files as shown in the image.








Installing the MongoDB server
Intalling the MongoDB server is not a time taking process,just open the command prompt and go the location of bin of the unzipped folder,in the meanwhile create the
database folder as MongoDB does not create the database itself.

execute the fallowing command mongod --dbpath "f://mongodatabase"
and press enter the fallowing screen show the out that your server is up and running on the default port 27017











Test your DB Installation
Open the web browser and type the fallowing addres http://loacalhost:27017/
The webpage displays the welcome page of mongoDB same as the image shown.









Connect to MongoDB
Open the command prompt, open the bin location






run the MongoDB as a Windows Service
open the command prompt and execute the fallowing command
mongod --dbpath "f:\mongodatabase" --logpath "f:\mongodatabase\logs.txt" --install --serviceName "MongoDB"
here shown the output on the console





The Next step is to verify from the service manager





Uninstall
Use the remove command shown in the image.




Create Database in the MongoDB
MongoDB does not provide any command or syntex to create database as provided with the relationship based
database,it creates the database on the fly when you try to insert the values first time in the database.

on the shell use show dbs command which shows the local(empty) database




use databasename command will create your MongoDB,but the database has not been created yet you can
verify the same by using show dbs command.
The database only created when you try to insert some document into the database
Define a collection name as employee and let try to insert some document inside it




New in Java 7

Working with java.nio.file package overcome the difficulties in copying and moving the files and directories which java really lacks of.
Java 7 provide directory tree traversal trough Files.walkFileTree Method which basically traverse the hierarchical folder structure
Path Objects
Path object represent the sequence of Directory structure to find the file resource
How to construct path object

Paths.get(“/BaseDir”);    // return path string “/BaseDir”

Paths.get(“/BaseDir”,”SubDir”);   // return the path string “/BaseDir/SubDir”

path object can be manipulated using the Path.resolve and Path.relativize,lets have a look
Path base =  Paths.get(“/BaseDir”);    //this is the base path

Path filePath = base.resolve(“SubDir/somefile.txt”);    // the filePath is “/BaseDir/SubDir/somefile.txt” while the base path remains “/BaseDir”
The very useful method of the Path class is Path.getFileName which inturn return the farthest element which is eighter a file or directory,lets have an example
suppose we have created the filePath as “/BaseDir/SubDir/somefile.txt”
filePath.getFileName()    // returns the name of the file as somefile.txt

suppose we have created the dirPath as “/BaseDir/SubDir/SomeDir”

dirPath.getFileName()     // return the directory name as SomeDir

How to copy a file

Path srcPath = …......
Path targetPath = …...............
Path basePath = …......
Files.copy(srcPath,targetPath.resolve(basePath.relativize(srcPath)));

Monday, June 4, 2012

Hibernate: Saving Collections

We have a Employee Class in which we have class field as empId,empName and addresses.
suppose an Employee can have multiple address, in our example we have considered that
Employee have office address as well as home address.
for saving these address we have used Set collection in our example.
Here is the Employee Class
//Employee.java

package com.test;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Employee {
 
 @Id
 @GeneratedValue(strategy=GenerationType.AUTO)
 private int empid;
 
 @Column(name="EMPLOYEE_NAME")
 private String empName;
 
 @ElementCollection
 private Set
addresses = new HashSet
(); public Set
getAddresses() { return addresses; } public void setAddresses(Set
addresses) { this.addresses = addresses; } public int getEmpid() { return empid; } public void setEmpid(int empid) { this.empid = empid; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } }
Here we have address class which is marked as @Embeddable
package com.test;

import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class Address {
 
 @Column(name="STREET")
 private String street;
 
 @Column(name="CITY")
 private String city;
 
 @Column(name="PINCODE")
 private String pincode;
 
 @Column(name="STATE")
 private String state;
 
 public String getStreet() {
  return street;
 }
 public void setStreet(String street) {
  this.street = street;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
 public String getPincode() {
  return pincode;
 }
 public void setPincode(String pincode) {
  this.pincode = pincode;
 }
 public String getState() {
  return state;
 }
 public void setState(String state) {
  this.state = state;
 }
 
}

for persisting these classes we need a hibernate configuration to our database here I used MySQL as database
look at Hibernate.cfg.xml
<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/HibernateDb</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>

        
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's current session context -->
        <property name="current_session_context_class">org.hibernate.context.ManagedSessionContext</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 class="com.test.Address"/>
        <mapping class="com.test.Employee"/>
        
    </session-factory>

</hibernate-configuration>

now we are ready to test our example here we have our main class
package com.test;

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

public class Main {

 
 public static void main(String[] args) {
  Employee emp1 = new Employee();
  emp1.setEmpName("Rajkumar Singh");
  
  Employee emp2 = new Employee();
  emp2.setEmpName("Sharad Singh");
  
  Address homeAddress = new Address();
  homeAddress.setCity("Bareilly");
  homeAddress.setStreet("121");
  homeAddress.setPincode("201301");
  homeAddress.setState("UP");
  
  Address officeAddress = new Address();
  officeAddress.setCity("Noida");
  officeAddress.setStreet("131");
  officeAddress.setPincode("201302");
  officeAddress.setState("UP");
  
  emp1.getAddresses().add(homeAddress);
  emp1.getAddresses().add(officeAddress);
  
  SessionFactory sf = new Configuration().configure().buildSessionFactory();
  Session session = sf.openSession();
  session.beginTransaction();
  session.save(emp1);  // saving emp1 
  session.getTransaction().commit();
  session.close();
  

 }

}

we we ran our main class two table have generated in the database with the name of Employee and Employee_addresses.

look at the console output
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Hibernate: insert into Employee (EMPLOYEE_NAME) values (?)
Hibernate: insert into Employee_addresses (Employee_empid, CITY, PINCODE, STATE, STREET) values (?, ?, ?, ?, ?)
Hibernate: insert into Employee_addresses (Employee_empid, CITY, PINCODE, STATE, STREET) values (?, ?, ?, ?, ?)