Java

Java is a set of computer software and specifications developed by Sun Microsystems, which was later acquired by the Oracle Corporation, that provides a system for developing application software and deploying it in a cross-platform computing environment. Java is used in a wide variety of computing platforms from embedded devices and mobile phones to enterprise servers and supercomputers.

Spring Logo

Spring Framework

The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications - on any kind of deployment platform. A key element of Spring is infrastructural support at the application level: Spring focuses on the "plumbing" of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.

Hibernate Logo

Hibernate Framework

Hibernate ORM is an object-relational mapping framework for the Java language. It provides a framework for mapping an object-oriented domain model to a relational database.

Tuesday, November 26, 2013

Install PostgreSQL9.1.9 Database Server on Fedora 17






"PostgreSQL is a powerful, open source object-relational database system. It has more than 15 years of active development and a proven architecture that has earned it a strong reputation for reliability, data integrity, and correctness."  

The following are the steps to install PostgreSQL9.1.9 in Fedora17.

Step-1: Change to root user

[ranga@ranga ~]$ su
Password:
[root@ranga ranga]#

Step-2: Install PostgreSQL Server
[root@ranga ~]# yum install postgresql-server

Step-3: Configure PostgreSQL Server

[root@ranga ~]# postgresql-setup initdb
Initializing database ... OK 
 
Step-8: Enable and Start PostgreSQL Server

Start server:
[root@ranga ~]# systemctl start postgresql.service

Enable postgresql:
[root@ranga ~]# systemctl enable postgresql.service


Creating a Database
Connect as user mypguser to new database

[root@ranga ~]# sudo su - postgres

Check that you can login.
-bash-4.2$ psql
psql (9.1.6)
Type "help" for help.

postgres=#

bash-4.2$ createdb RangaDB

bash-4.2$ psql RangaDB
psql (9.1.9)
Type "help" for help.

 

Create Database User

RangaDB=# CREATE ROLE ranga WITH SUPERUSER LOGIN PASSWORD 'ranga';
CREATE ROLE

or

RangaDB=# CREATE USER ranga WITH PASSWORD 'ranga';
CREATE ROLE

RangaDB=# psql -h localhost -U ranga ranga
RangaDB-#

If you get errors like:
psql: FATAL:  Peer authentication failed for user "ranga"
edit pg_hba.conf in  /var/lib/pgsql/data/pg_hba.conf

change peer and ident to md5.
# TYPE  DATABASE        USER            ADDRESS                 METHOD
# "local" is for Unix domain socket connections only
local all all peer
# IPv4 local connections:
host all all 127.0.0.1/32 ident
# IPv6 local connections:
host all all ::1/128 ident
to

# TYPE  DATABASE        USER            ADDRESS                 METHOD
# "local" is for Unix domain socket connections only
local   all             all                                     md5
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5


Quit from the database
RangaDB=# \q

bash-4.2$ psql -d RangaDB -U ranga
could not change directory to "/root"
Password for user ranga:
psql (9.1.9)
Type "help" for help.

RangaDB=# create table test(id int);
CREATE TABLE
RangaDB=# select * from test;
 id
----
(0 rows)

RangaDB=# insert into test values(1);
INSERT 0 1
RangaDB=# select * from test;
 id
----
  1
(1 row)

RangaDB=# drop table test;
DROP TABLE
 
Changing Password:

[root@ranga trunk]# passwd postgres
Changing password for user postgres.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.
Install PostgreSQL GUI Client

If you want to manage PostgreSQL using a GUI client, you need to install pgadmin3.
[root@ranga ranga]# sudo yum install pgadmin3

To list available packages: 
[root@ranga ranga]# yum list postgres*

Removing (or) Uninstalling PostgreSQL:

 
[ranga@ranga trunk]$ yum erase postgresql*
yum remove postgresql postgresql-devel postgresql-server
 

[root@ranga ~]# rpm -e --nodeps postgresql-libs

PostgreSQL Upgrade:
http://docs.1h.com/PostgreSQL_Upgrade


Installing pgAdmin:

The command line administration will be good for the people who has full experience on PostgreSQL, but for the beginner pgAdmin will be best option to manage the databases. By default pgAdmin packages available on fedora repository, so just issue the following command to install it.

Install pgAdmin3:
[root@ranga ranga]# yum install pgadmin3

Start pgAdmin3:
[root@ranga ranga]# pgadmin3

Now Connect to the database server using pgAdmin.

------------------------------------------------------------------------------------------------

Drop all tables:

DROP SCHEMA public CASCADE;  
CREATE SCHEMA public; 

Monday, November 25, 2013

How to reset the MySQL Server admin/root Password

The following are the steps to restore/reset MySQL admin/root password:

Step-1: Stop your MySQL server

There are many ways to do this:
  • service mysql stop  or
  • service mysqld stop
[root@ranga ranga]# service mysqld stop

Step-2: Start your MySQL server in safe mode by using following command.

mysqld_safe --skip-grant-tables --autoclose

It will start the MySQL server with out asking any passwords.

[root@ranga ranga]# mysqld_safe --skip-grant-tables --autoclose

Step-3: Connect to MySQL server.

[root@ranga ranga]# mysql
Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 1 to server version: 3.23.41

Type 'help;' or 'h' for help. Type 'c' to clear the buffer.


Step-4: Run the below commands, to setup new password for the root or admin.
 
mysql> USE mysql
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed


mysql> UPDATE mysql.user SET Password=
PASSWORD("ranga")
-> WHERE user="root";

Query OK, 2 rows affected (0.04 sec)
Rows matched: 2 Changed: 2 Warnings: 0

mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)


The flush statement tells the server to reload the grant tables into memory so that it notices the password change. 

mysql> exit;


Now your MySQL Server password is successfully reseted.

Step-5: Restart MySQL server. This can be done in two ways.

1. Stop and Start the Server

[root@ranga ranga]# service mysqld stop
[root@ranga ranga]# service mysqld start

(or)

2. Directly Restart the Server

[root@ranga ranga]# service mysqld restart

Step-6: Now login with your new password

[root@ranga ranga]#mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 5 to server version: 4.1.15

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>

Thursday, November 21, 2013

Hibernate4 example by using PostgreSQL DB.

Prerequisite requirement

- Installed and configured Maven, MySQL, Eclipse IDE.
- See more at: http://www.developer.am/documentation/hibernate/?page=maven-spring-hibernate-mysql-example#sthash.8UVHMaBr.dpuf

Prerequisite requirement

- Installed and configured Maven, MySQL, Eclipse IDE.
- See more at: http://www.developer.am/documentation/hibernate/?page=maven-spring-hibernate-mysql-example#sthash.8UVHMaBr.dpufPrerequisite requirement
- Installed and configured Maven, MySQL, Eclipse IDE.
- See more at: http://www.developer.am/documentation/hibernate/?page=maven-spring-hibernate-mysql-example#sthash.8UVHMaBr.dpu

Prerequisite requirement

- Installed and configured Maven, MySQL, Eclipse IDE.
- See more at: http://www.developer.am/documentation/hibernate/?page=maven-spring-hibernate-mysql-example#sthash.8UVHMaBr.
Step1: Create a Java project with Maven

Run the following command in terminal or command prompt to generate a standard java project.
Create a quick project file structure with Maven command ‘mvn archetype:generate‘ - See more at: http://www.developer.am/documentation/hibernate/?page=maven-spring-hibernate-mysql-example#sthash.8UVHMaBr.dpuf

[ranga@ranga gradle]$ mvn archetype:generate -DgroupId=com.ranga -DartifactId=HibernateExampleUsingPostgreSQL -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Project structure:

HibernateExampleUsingPostgreSQL/
├── pom.xml
└── src
    ├── main
    │   └── java
    │       └── com
    │           └── ranga
    │               └── App.java
    └── test
        └── java
            └── com
                └── ranga
                    └── AppTest.java

9 directories, 3 files

Step2: Compile and Run the newly created Java project.

[ranga@ranga HibernateExampleUsingPostgreSQL]$ mvn clean install

[ranga@ranga HibernateExampleUsingPostgreSQL]$ java -cp target/HibernateExampleUsingPostgreSQL-1.0-SNAPSHOT.jar com.ranga.App

Output:
Hello World!

Step3: Convert to Eclipse Project
[ranga@ranga HibernateExampleUsingPostgreSQL]$ mvn eclipse:eclipse

Step4: Import converted Project into Eclipse

OpenEclipse IDE, Choose File –> Import –> General folder, Existing Projects into Workspace –>Choose your project folder location.

Step5: Add the Hibernate4.x and Oracle dependencies

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">   
   
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ranga</groupId>
    <artifactId>HibernateExampleUsingPostgreSQL</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>HibernateExampleUsingPostgreSQL</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <!-- JBoss repository for Hibernate -->
    <repositories>
        <repository>
            <id>JBoss repository</id>
            <url>http://repository.jboss.org/nexus/content/groups/public/</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>

        <!-- Hibernate framework -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.2.7.Final</version>
        </dependency>

        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.12.1.GA</version>
        </dependency>

        <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901.jdbc4</version>
        </dependency> 


    </dependencies>

</project>

Step6: Create a resources folder

Create a new folder called resources under src/main. Here we are adding the Configuration files and Mapping files.

Project structure:

HibernateExampleUsingPostgreSQL/
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── ranga
    │   │           └── App.java
    │   └── resources
    ├── pom.xml
    └── test
        └── java
            └── com
                └── ranga
                    └── AppTest.java

10 directories, 6 files


Step7: Hibernate configuration file
Create a Hibernate configuration file and put under the resources root folder, “src/main/resources/hibernate.cfg.xml“. Add the following content.

hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">org.postgresql.Driver</property>
        <property name="connection.url">jdbc:postgresql://127.0.0.1:5432/RangaDB</property>
        <property name="connection.username">ranga</property>
        <property name="connection.password">ranga</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</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.internal.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">create</property>

        <mapping resource="com/ranga/mapping/Person.hbm.xml" />
    </session-factory>
</hibernate-configuration>

Step8: Hibernate Mapping file

Create a Person.hbm.xml file and put it in “src/main/resources/com/ranga/mapping“ folder. 

Person.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.ranga.mapping">
    <class name="Person" table="Persons">
        <id name="id" column="Person_ID" type="long">
            <generator class="native"/>                     
        </id>
        <property name="firstName" column="FirstName" type="string"/>
        <property name="lastName" column="LastName" type="string"/>
        <property name="age" column="Age" type="integer"/>      
    </class>
</hibernate-mapping>

Project structure:

HibernateExampleUsingPostgreSQL/
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── ranga
    │   │           └── App.java
    │   └── resources
    │       ├── com
    │       │   └── ranga
    │       │       └── mapping
    │       │           └── Person.hbm.xml
    │       └── hibernate.cfg.xml
    ├── pom.xml
    └── test
        └── java
            └── com
                └── ranga
                    └── AppTest.java

13 directories, 8 files
 

Step9: POJO class or Model class

Create a Person.java file and put it in “src/main/java/com/ranga/mapping

Person.java

package com.ranga.mapping;

import java.io.Serializable;

public class Person implements Serializable {
   
    private long id;
    private String firstName;
    private String lastName;
    private int age;
   
    public long getId() {
        return id;
    }
    public void setId(long 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;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Person [id=" + id + ", firstName=" + firstName + ", lastName="
                + lastName + ", age=" + age + "]";
    }           
}
 
Step10: Hibernate Utility class

Create a HibernateUtil.java class to take care of Hibernate start up and retrieve the session easily. Create a util folder and put this file in it, “src/main/java/com/ranga/util”.

HibernateUtil.java

package com.ranga.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
        private static final SessionFactory sessionFactory;
        private static final ServiceRegistry serviceRegistry;
        static {
                try {
                        // Create the SessionFactory from hibernate.cfg.xml
                        Configuration configuration = new Configuration();
                        configuration.configure();
                        serviceRegistry = new ServiceRegistryBuilder().applySettings(
                                        configuration.getProperties()).buildServiceRegistry();
                        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
                } 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;
        }

        public static void closeSessionFactory() {
        if (sessionFactory != null)
            sessionFactory.close();
    }
}


Step 11: Client Application

App.java

package com.ranga;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.ranga.mapping.Person;
import com.ranga.util.HibernateUtil;

public class App {
    public static void main(String[] args) {
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        Person p1 = new Person();
        p1.setFirstName("ranga");
        p1.setLastName("reddy");
        p1.setAge(25);
        long personId = (Long) session.save(p1);
        session.getTransaction().commit();
       
        Person person = (Person) session.get(Person.class, personId);       
        System.out.println(person);
               
        session.close();
    }
}

Project structure:

HibernateExampleUsingPostgreSQL/
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── ranga
    │   │           ├── App.java
    │   │           ├── mapping
    │   │           │   └── Person.java
    │   │           └── util
    │   │               └── HibernateUtil.java
    │   └── resources
    │       ├── com
    │       │   └── ranga
    │       │       └── mapping
    │       │           └── Person.hbm.xml
    │       └── hibernate.cfg.xml
    ├── pom.xml
    └── test
        └── java
            └── com
                └── ranga
                    └── AppTest.java





 

15 directories, 10 files

Now the Hibernate Application is ready.

Step12: Run the hibernate client application

Person [id=1, firstName=ranga, lastName=reddy, age=25]

Download
 

Tuesday, November 19, 2013

List of Hibernate SQL Dialects (hibernate.dialect)



Purpose: We all know there are different versions of Oracle... Oracle 11g, Oracle 10g, Oracle9i, Oracle8. The driver we would use would be a common for all of these. But the dialect we use is specific to each one of them, which helps Hibernate in generating optimized queries to those specific versions of database.


Dialect (hibernate.dialect)  is a property of hibernate, which is used to connect to particular database. Hibernate supports many databases. This property makes Hibernate generates the appropriate SQL for the chosen database. This idea makes us to develop database vendor independent application.


Note: This is not mandatory to be given in hibernate.cfg.xml file.


Following is the lists of Dialects provided by hibernate to connect different databases.

Database
Dialect Property
DB2
org.hibernate.dialect.DB2Dialect
DB2 AS/400
org.hibernate.dialect.DB2400Dialect
DB2 OS390
org.hibernate.dialect.DB2390Dialect
PostgreSQL 8.1
org.hibernate.dialect.PostgreSQL81Dialect
PostgreSQL 8.2 and later
org.hibernate.dialect.PostgreSQL82Dialect
MySQL5
org.hibernate.dialect.MySQL5Dialect
MySQL5 with InnoDB
org.hibernate.dialect.MySQL5InnoDBDialect
MySQL with MyISAM
org.hibernate.dialect.MySQLMyISAMDialect
Oracle (any version)
org.hibernate.dialect.OracleDialect
Oracle 9i
org.hibernate.dialect.Oracle9iDialect
Oracle 10g
org.hibernate.dialect.Oracle10gDialect
Oracle 11g
org.hibernate.dialect.Oracle10gDialect
Sybase ASE 15.5
org.hibernate.dialect.SybaseASE15Dialect
Sybase ASE 15.7
org.hibernate.dialect.SybaseASE157Dialect
Sybase Anywhere
org.hibernate.dialect.SybaseAnywhereDialect
Microsoft SQL Server 2000
org.hibernate.dialect.SQLServerDialect
Microsoft SQL Server 2005
org.hibernate.dialect.SQLServer2005Dialect
Microsoft SQL Server 2008
org.hibernate.dialect.SQLServer2008Dialect
SAP DB
org.hibernate.dialect.SAPDBDialect
Informix
Informix org.hibernate.dialect.InformixDialect
HypersonicSQL
org.hibernate.dialect.HSQLDialect
H2 Database
org.hibernate.dialect.H2Dialect
Ingres
org.hibernate.dialect.IngresDialect
Progress
org.hibernate.dialect.ProgressDialect
Mckoi SQL
org.hibernate.dialect.MckoiDialect
Interbase
org.hibernate.dialect.InterbaseDialect
Pointbase
org.hibernate.dialect.PointbaseDialect
FrontBase
org.hibernate.dialect.FrontbaseDialect
Firebird
org.hibernate.dialect.FirebirdDialect

Saturday, November 16, 2013

Hibernate4.X Application example by using Maven

Prerequisite requirement

- Installed and configured Maven, MySQL, Eclipse IDE.
- See more at: http://www.developer.am/documentation/hibernate/?page=maven-spring-hibernate-mysql-example#sthash.8UVHMaBr.dpuf

Prerequisite requirement

- Installed and configured Maven, MySQL, Eclipse IDE.
- See more at: http://www.developer.am/documentation/hibernate/?page=maven-spring-hibernate-mysql-example#sthash.8UVHMaBr.dpufPrerequisite requirement
- Installed and configured Maven, MySQL, Eclipse IDE.
- See more at: http://www.developer.am/documentation/hibernate/?page=maven-spring-hibernate-mysql-example#sthash.8UVHMaBr.dpu

Prerequisite requirement

- Installed and configured Maven, MySQL, Eclipse IDE.
- See more at: http://www.developer.am/documentation/hibernate/?page=maven-spring-hibernate-mysql-example#sthash.8UVHMaBr.
Step1: Create a Java project with Maven

Run the following command in terminal or command prompt to generate a standard java project.
Create a quick project file structure with Maven command ‘mvn archetype:generate‘ - See more at: http://www.developer.am/documentation/hibernate/?page=maven-spring-hibernate-mysql-example#sthash.8UVHMaBr.dpuf

[ranga@ranga gradle]$ mvn archetype:generate -DgroupId=com.ranga -DartifactId=HibernateExampleUsingMaven -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Project structure:

HibernateExample2/
├── pom.xml
└── src
    ├── main
    │   └── java
    │       └── com
    │           └── ranga
    │               └── App.java
    └── test
        └── java
            └── com
                └── ranga
                    └── AppTest.java

9 directories, 3 files

Step2: Compile and Run the newly created Java project.

[ranga@ranga HibernateExampleUsingMaven]$ mvn clean install

[ranga@ranga HibernateExampleUsingMaven]$ java -cp target/HibernateExampleUsingMaven-1.0-SNAPSHOT.jar com.ranga.App

Output:
Hello World!

Step3: Convert to Eclipse Project
[ranga@ranga HibernateExampleUsingMaven]$ mvn eclipse:eclipse

Step4: Import converted Project into Eclipse

OpenEclipse IDE, Choose File –> Import –> General folder, Existing Projects into Workspace –>Choose your project folder location.

Step5: Add the Hibernate4.x and Oracle dependencies

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">   
   
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ranga</groupId>
    <artifactId>HibernateExampleUsingMaven</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>HibernateExampleUsingMaven</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <!-- JBoss repository for Hibernate -->
    <repositories>
        <repository>
            <id>JBoss repository</id>
            <url>http://repository.jboss.org/nexus/content/groups/public/</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>

        <!-- Hibernate framework -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.2.7.Final</version>
        </dependency>

        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.12.1.GA</version>
        </dependency>

        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0</version>
        </dependency>

    </dependencies>

</project>

Step6: Create a resources folder

Create a new folder called resources under src/main. Here we are adding the Configuration files and Mapping files.

Project structure:

HibernateExample2/
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── ranga
    │   │           └── App.java
    │   └── resources
    ├── pom.xml
    └── test
        └── java
            └── com
                └── ranga
                    └── AppTest.java

10 directories, 6 files


Step7: Hibernate configuration file
Create a Hibernate configuration file and put under the resources root folder, “src/main/resources/hibernate.cfg.xml“. Add the following content.
hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>


        <!-- Database connection settings -->
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
        <property name="connection.username">ranga</property>
        <property name="connection.password">ranga</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.Oracle10gDialect</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">create</property>


       <!-- Mapping files  -->  

       <mapping resource="com/ranga/mapping/Employee.hbm.xml" />

    </session-factory>
</hibernate-configuration>


Step8: Hibernate Mapping file

Create a Employee.hbm.xml file and put it in “src/main/resources/com/ranga/mapping“ folder. 

Employee.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.ranga.mapping">
    <class name="Employee" table="Employees">
        <id name="id" type="java.lang.Long">
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String" />
        <property name="age" type="java.lang.Integer">
    </class>
</hibernate-mapping> 


Project structure:

HibernateExample2/
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── ranga
    │   │           └── App.java
    │   └── resources
    │       ├── com
    │       │   └── ranga
    │       │       └── mapping
    │       │           └── Employee.hbm.xml
    │       └── hibernate.cfg.xml
    ├── pom.xml
    └── test
        └── java
            └── com
                └── ranga
                    └── AppTest.java

13 directories, 8 files
 

Step9: POJO class or Model class

Create a Employee.java file and put it in “src/main/java/com/ranga/mapping

Employee.java

package com.ranga.mapping;

import java.io.Serializable;

public class Employee implements Serializable {
        private long id;
        private String name;
        private int age;

        public long getId() {
                return id;
        }
        public void setId(long id) {
                this.id = id;
        }
        public String getName() {
                return name;
        }
        public void setName(String name) {
                this.name = name;
        }
        public int getAge() {
                return age;
        }
        public void setAge(int age) {
                this.age = age;
        }

        @Override
        public String toString() {
           return "Employee [id = "+id+", name = "+name+", age = "+age+"]";
        }
}


Step10: Create Hibernate Utility class

Create a HibernateUtil.java class to take care of Hibernate start up and retrieve the session easily. Create a util folder and put this file in it, “src/main/java/com/ranga/util”.

HibernateUtil.java

package com.ranga.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
        private static final SessionFactory sessionFactory;
        private static final ServiceRegistry serviceRegistry;
        static {
                try {
                        // Create the SessionFactory from hibernate.cfg.xml
                        Configuration configuration = new Configuration();
                        configuration.configure();
                        serviceRegistry = new ServiceRegistryBuilder().applySettings(
                                        configuration.getProperties()).buildServiceRegistry();
                        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
                } 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;
        }

        public static void closeSessionFactory() {
        if (sessionFactory != null)
            sessionFactory.close();
    }
}



Step 11: Client Application

App.java

package com.ranga;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.ranga.mapping.Employee;
import com.ranga.util.HibernateUtil;

public class App
{
    public static void main( String[] args )
    {
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();

        Employee employee = new Employee();
        employee.setName("Ranga Reddy");
        employee.setAge(25);

        long employeeId  = (Long)session.save(employee);
        employee = (Employee) session.get(Employee.class, employeeId);

        System.out.println(employee);

        session.close();
    }
}


Project structure:

HibernateExample2/
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── ranga
    │   │           ├── App.java
    │   │           ├── mapping
    │   │           │   └── Employee.java
    │   │           └── util
    │   │               └── HibernateUtil.java
    │   └── resources
    │       ├── com
    │       │   └── ranga
    │       │       └── mapping
    │       │           └── Employee.hbm.xml
    │       └── hibernate.cfg.xml
    ├── pom.xml
    └── test
        └── java
            └── com
                └── ranga
                    └── AppTest.java

15 directories, 10 files


Now the Hibernate Application is ready.

Step12: Run the hibernate client application

Employee [id = 1, name = Ranga Reddy, age = 25]

Download