MultiThread – How to Run Multiple Threads Concurrently in Java? ExecutorService Approach

Standard

Let’s take a look at this example again: How to get Ping Status of any HTTP End Point in Java?

Have you noticed the thread execution for that example? It’s sequential. What if you have 500 endpoints? I bet you have to wait for at least 5 mins to get result. Which I’m sure is not the best solution.

Now what? The correct question would be:

  • How to Run multiple threads concurrently?
  • How to implement multiple threads in Java?
  • How do I run different threads in Java?
  • Java – Where is Multithreading Programming Tutorial?
  • Thread: How to use multiple threads to speed processing?

ExecutorService Approach is your answer.

An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.

An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService. The shutdown() method will allow previously submitted tasks to execute before terminating, while the shutdownNow()method prevents waiting tasks from starting and attempts to stop currently executing tasks.

Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. An unused ExecutorService should be shut down to allow reclamation of its resources.

Method submit extends base method Executor.execute (java.lang.Runnable) by creating and returning a Future that can be used to cancel execution and/or wait for completion. Methods invokeAny and invokeAll perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete. (Class ExecutorCompletionService can be used to write customized variants of these methods.)

The Executors class provides factory methods for the executor services provided in this package.

  • java – ExecutorService, how to wait for all tasks to finish?
  • A Guide to the Java ExecutorService
  • Java Thread Pool – ExecutorService explanation

Below is a simple Java Example which explains the usage of ExecutorService.

Output:

Now checkout the result. It should be in just seconds. I hope you find this helpful. Try running this more than one time and you may see different result as all threads are executing in parallels and who ever gets fast result, you will see result posted in Eclipse console.

How to setup user authentication in MongoDB 4.0

Standard

Creating the users

Let’s start, for real, by creating the actual users. Open your mongo shell and switch to the admin database:

use admin

Create the “admin” user (you can call it whatever you want)

db.createUser({ user: "admin", pwd: "adminpassword", roles: [{ role: "userAdminAnyDatabase", db: "admin" }] })

Don’t panic with all these brackets. We’re passing an “user” object to the createUser function, which contains a “roles” array. In the array we have one “role” object, which defines what the user can do and on which database.

In this case we’re giving the user the userAdminAnyDatabase role. This means that the admin user will be able manage (create, update, delete) users on all the databases of the MongoDB instance.

Make sure you use a safe password for the admin user, preferably generated by a password manager.

You can check that the user has been correctly created with this command:

db.auth("admin", "adminpassword")

The command will log you in as admin. Now exit the shell:

exit

We are now going to enable authentication on the MongoDB instance, by modifying the mongod.conf file. If you’re on Linux:

sudo nano /etc/mongod.conf

Add these lines at the bottom of the YAML config file:

security:
    authorization: enabled

This will enable authentication on your database instance. With nano, save with CTRL+X and confirm with y.

Now restart the mongod service (Ubuntu syntax).

sudo service mongod restart

You can check if the service is up with:

sudo service mongod status

Let’s go back in the mongo shell. Switch to the database admin and authenticate with the previously created user (called “admin”). Given that the user has the “userAdmin” role, it will be able to create and manage other users.

use admin
db.auth("admin", "adminpassword")

Now we will switch to an already created database and create a new user specifically for the database.

The following command will create an user with the role of dbOwner on the database. The dbOwner role will give to the user read and write permissions on all the collections of the database.

use yourdatabase
db.createUser({ user: "youruser", pwd: "yourpassword", roles: [{ role: "dbOwner", db: "yourdatabase" }] })

Check that everything went fine by trying to authenticate, with the db.auth(user, pwd) function.

db.auth("youruser", "yourpassword")
show collections

And that’s it, your MongoDB instance is now secured, provided that you used strong passwords.

When connecting with your favourite MongoDB Client from an application, use a connection string that will look like this:

mongodb://youruser:yourpassword@localhost/yourdatabase

Now, one last thing…

Protecting from external access

We’re now going to check that the MongoDB instance is listening on the local loopback interface only. This means that the DBMS will be accepting connections to the databases only when they come from the host itself.

You can of course adapt this to your needs, for example by enabling access on a private network interface, but the important thing to understand is that you should carefully decide which interfaces MongoDB should listen on. You should therefore avoid to expose the instance on the Internet if you don’t require to access it from the outside. And even if you do, there are much better ways to do that, for example by using an SSH tunnel. But that’s another story.

So, open mongod.conf in edit mode again, as we’re going to check out the net.bindIp option. That option tells the mongod process on which interfaces it should listen.

Examples of bindIp configuration

net:
    bindIp: 127.0.0.1

With this configuration, MongoDB will listen on 127.0.0.1 only (localhost). It means that you’ll be able to connect to your database only from the local machine.

NOTE: 127.0.0.1 is the default bind interface starting with MongoDB 3.6.0.

net:
    bindIp: 0.0.0.0

With this configuration, MongoDB will be listening on 0.0.0.0 (“all the networks”). It means that mongod will listen on all the interfaces configured on your system. Pay attention that in this way you are likely going to allow everyone on the Internet to access your database (as far as they have the credentials, of course, so pay particular attention to poor passwords).

You can also make MongoDB listen on more than one interface, by separing them with commas. This is useful if you want to make MongoDB listen on localhost and a private network interface.

net:
    bindIp: 127.0.0.1,172.21.200.200

A solution that you could consider is to set the bindIp option to 0.0.0.0 and then configure a firewall to filter incoming TCP requests on the MongoDB port and allow them only on specific interfaces.

install mongoDB on Linux

Standard

1) Create a /etc/yum.repos.d/mongodb-org-4.0.repo file so that you can install MongoDB directly using yum:

go to directory: /etc/yum.repos.d/
Create file: vi mongodb-org-4.0.repo
Paste data:
[mongodb-org-4.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.0.asc

2) Install the MongoDB packages.
sudo yum install -y mongodb-org

3) Start MongoDB.
sudo service mongod start

4) Begin using MongoDB.
mongo –host 127.0.0.1:27017

Shell script to import JSON files in mongodb

Standard
  • Following script will find all files in directory path mentioned below in “DIR” variable.
  • Read each file name in loop & execute mongodb import command i.e
    • mongoimport -d DATABASE_NAME -c TABLE_NAME –file FILE_PATH\FILE_NAME.json

#!/bin/sh

DIR=”NsBackupFiles/”
for eachFile in “$DIR”*
do
fileName=`echo $eachFile | cut -d’/’ -f 2`
tableName=`echo $fileName | cut -d’_’ -f 1`
echo $tableName
mongoimport -d ns_backup -c $tableName –file $eachFile
done

How to loop ArrayList in Java

Standard

There are four ways to loop ArrayList:

  1. For Loop
  2. Advanced for loop
  3. While Loop
  4. Iterator

Lets have a look at the below example – I have used all of the mentioned methods for iterating list.

import java.util.*;
public class LoopExample {
   public static void main(String[] args) {

      ArrayList<Integer> arrlist = new ArrayList<Integer>();
      arrlist.add(14);
      arrlist.add(7);
      arrlist.add(39);
      arrlist.add(40);

      /* For Loop for iterating ArrayList */
      System.out.println("For Loop");
      for (int counter = 0; counter < arrlist.size(); counter++) { 		      
          System.out.println(arrlist.get(counter)); 		
      }   		

      /* Advanced For Loop*/ 		
      System.out.println("Advanced For Loop"); 		
      for (Integer num : arrlist) { 		      
           System.out.println(num); 		
      }

      /* While Loop for iterating ArrayList*/ 		
      System.out.println("While Loop"); 		
      int count = 0; 		
      while (arrlist.size() > count) {
	 System.out.println(arrlist.get(count));
         count++;
      }

      /*Looping Array List using Iterator*/
      System.out.println("Iterator");
      Iterator iter = arrlist.iterator();
      while (iter.hasNext()) {
         System.out.println(iter.next());
      }
   }
}

Output:

For Loop
14
7
39
40
Advanced For Loop
14
7
39
40
While Loop
14
7
39
40
Iterator
14
7
39
40

How to iterate arraylist elements using Enumeration interface

import java.util.Enumeration;
import java.util.ArrayList;
import java.util.Collections;
 
public class EnumExample {
 
   public static void main(String[] args) {
      //create an ArrayList object
      ArrayList<String> arrayList = new ArrayList<String>();
 
      //Add elements to ArrayList
      arrayList.add("C");
      arrayList.add("C++");
      arrayList.add("Java");
      arrayList.add("DotNet");
      arrayList.add("Perl");
 
      // Get the Enumeration object
      Enumeration<String> e = Collections.enumeration(arrayList);
 
      // Enumerate through the ArrayList elements
      System.out.println("ArrayList elements: ");
      while(e.hasMoreElements())
      System.out.println(e.nextElement());
   }
}

Output:

ArrayList elements: 
C
C++
Java
DotNet
Perl

JDBC Connection Code for MYSQL/ORACLE DB

Standard

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

public class dataBaseConnManager {
static Connection conn = null;
static Statement stmt = null;
constant cnst = new constant();
public dataBaseConnManager() {
try {
if(conn==null || stmt == null || stmt.isClosed() == true)
{
conn = null;
stmt = null;
constant cnst = new constant();
// JDBC driver name and database URL

final String JDBC_DRIVER = “com.mysql.jdbc.Driver”; //FOR MYSQL

//final String JDBC_DRIVER = “oracle.jdbc.driver.OracleDriver”; //FOR ORACLE

final String DB_URL = “jdbc:mysql://localhost/”+cnst.dataBaseName; //FOR MYSQL

//final String DB_URL = “jdbc:oracle:thin:@129.146.79.106:1521:orcl”; //FOR ORACLE

final String USER = cnst.dataBaseUserName;
final String PASS = cnst.dataBasePassword;
try{
//STEP 2: Register JDBC driver
Class.forName(“com.mysql.jdbc.Driver”); //FOR MYSQL

//Class.forName(“oracle.jdbc.driver.OracleDriver”); //FOR ORACLE

//STEP 3: Open a connection
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
stmt = conn.createStatement();

}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

Hibernate Maven Example

Standard

1. Introduction

1.1 Hibernate

  • Object-Relational Mapping or ORM is the programming technique to map application domain model objects to the relational database tables
  • Hibernate is Java-based ORM tool that provides the framework for mapping application domain objects to the relational database tables and vice versa. It provides reference implementation of Java Persistence API, that makes it a great choice as an ORM tool with benefits of loose coupling
  • Framework provides option to map plain old Java objects to traditional database tables with the use of JPA annotations as well as XML based configuration
// Fig. 1: Hibernate Overview

Fig. 1: Hibernate Overview

1.2 Hibernate Architecture

There are 4 layers in the Hibernate architecture i.e. Java Application Layer, Hibernate Framework Layer, Backend API Layer, and the Database Layer. Let’s understand the diagram of Hibernate architecture.

Fig. 2: Hibernate Architectural Diagram

Fig. 2: Hibernate Architectural Diagram

For creating the first Hibernate application, we must know the elements of the Hibernate architecture. They are as follows:

Element Description
SessionFactory The SessionFactory is a factory of session and client of Connection Provider. It holds second level cache (optional) of data
Session The session object provides an interface between the application and data stored in the database. It is a short-lived object and wraps the JDBC connection. It is a factory of TransactionQuery and Criteria and holds the first-level cache of data. The Session interface provides methods to INSERTUPDATE, and DELETE the objects
Transaction The transaction object specifies the atomic unit of work and is an optional parameter in the Hibernate framework
ConnectionProvider It is a factory of JDBC connections and abstracts the application from DriverManager or DataSource. It is optional parameter in the Hibernate framework
TransactionFactory It is a factory of Transaction and is again an optional parameter in the Hibernate framework

1.3 Hibernate Benefits

There are many advantages of using the Hibernate framework, for e.g.

    • Hibernate framework is open-source and lightweight
    • The performance of Hibernate framework is fast and supports smart fetching techniques because of the internal caching mechanism
    • Hibernate framework provides the facility to create the database tables automatically
    • With the help of HQL (Hibernate Query Language), the generated SQL queries are independent of databases
    • Provides query facilities to fetch the data from multiple databases, and supports transaction management and automatic key generations
    • Provides APIs for storing and retrieving the Java objects directly to and from the database
    • Framework takes care of the mapping Java classes to database tables using XML files or annotations

1.4 Maven

Apache Maven is one of the most popular Software project management and comprehension tool, based on a central piece of information called Project Object Model (POM). Project-based on Maven gets its compilation, build, reporting and documentation instructions from an XML file named pom.xml.

pom.xml is a standard XML file complying Maven scheme. It contains the dependencies required by the project, the plugins that the project might need, the repository that the project can look into to search for the dependencies, the parent/child module information in case of multi-module projects, the profile to support different builds for different situations/environments and many more features.

1.4.1 Ant vs. Maven

Ant and Maven both are build tools provided by Apache. The main purpose of these technologies is to ease the build process of a project. There are many differences between Ant and Maven and they are given below:

Ant Maven
Ant doesn’t have formal conventions, so we need to provide information of the project structure in build.xml file Maven has a convention to place source code, compiled code etc. So we don’t need to provide information about the project structure in pom.xml file
Ant is procedural, you need to provide information about what to do and when to do through code. You need to provide order Maven is declarative, everything you define in the pom.xml file
It is mainly a build tool and has no life cycle It is a project management tool and has its own lifecycle
The Ant scripts are not reusable The Maven plugins are reusable

1.5 Download and Install Hibernate

You can read this tutorial in order to download and install Hibernate in the Eclipse IDE.

1.6 Download and Install MySQL

You can watch this video in order to download and install the MySQL database on your Windows operating system.

1.7 Download and Install Maven

You can read this tutorial in order to download and install Maven on your Windows operating system.

Now, open up the Eclipse IDE and let’s see how to implement Maven!

2. Hibernate Maven Example

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8, MySQL Database and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Fig. 3: Hibernate Maven Application Project Structure

Fig. 3: Hibernate Maven Application Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Fig. 3: Create Maven Project

Fig. 3: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location‘ will be selected. Select the ‘Create a simple project (skip archetype selection)‘ checkbox and just click on next button to proceed.

Fig. 4: Project Details

Fig. 4: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default 0.0.1-SNAPSHOT.

Fig. 5: Archetype Parameters

Fig. 5: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

1
2
3
4
5
6
7
    <modelVersion>4.0.0</modelVersion>
    <groupId>HibernateMaven</groupId>
    <artifactId>HibernateMaven</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
</project>

We can start adding the dependencies that developers want like Hibernate, MySQL etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Database & Table Creation

The following MySQL script is used to create a database called tutorialDb with table: user_table. Open MySQL terminal or workbench terminal and execute the script.

01
02
03
04
05
06
07
08
09
10
11
12
13
CREATE DATABASE IF NOT EXISTS tutorialDb;
USE tutorialDb;
DROP TABLE IF EXISTS user_table;
CREATE TABLE user_table (
  user_id int(20) NOT NULL,
  user_name varchar(255) NULL,
  created_by VARCHAR (255) NOT NULL,
  created_date DATE NOT NULL,
  PRIMARY KEY (user_id)
);

If everything goes well, the table will be shown in the MySQL workbench.

Fig. 6: Database & Table Creation

Fig. 6: Database & Table Creation

3.2 Maven Dependencies

Here, we specify only two dependencies for Hibernate Core and MySQL Connector. Rest dependencies will be automatically resolved by Maven, such as Hibernate JPA and Hibernate Commons Annotations. The updated file will have the following code:

pom.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    <modelVersion>4.0.0</modelVersion>
    <groupId>HibernateMaven</groupId>
    <artifactId>HibernateMaven</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <dependencies>
        <!-- Hibernate 4.3.6 Final -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.6.Final</version>
        </dependency>
        <!-- Mysql Connector -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.21</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>${project.artifactId}</finalName>
    </build>
</project>

Maven will download all Hibernate and MySQL libraries automatically and it will put them into Maven’s local repository. At the same time, Maven will add the downloaded libraries into Eclipse .classpath file for dependency purpose.

3.3 Java Class Creation

Let’s create the required Java files. Right-click on src/main/java folder, New -> Package.

Fig. 7: Java Package Creation

Fig. 7: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.hibernate.maven.

Fig. 8: Java Package Name (com.jcg.hibernate.maven)

Fig. 8: Java Package Name (com.jcg.hibernate.maven)

Once the package is created in the application, we will need to create the model and implementation classes. Right-click on the newly created package: New -> Class.

Fig. 9: Java Class Creation

Fig. 9: Java Class Creation

A new pop window will open and enter the file name as User. The model class will be created inside the package: com.jcg.hibernate.maven.

Fig. 10: Java Class (User.java)

Fig. 10: Java Class (User.java)

Repeat the step (i.e. Fig. 9) and enter the filename as AppMain. The implementation class will be created inside the package: com.jcg.hibernate.batch.processing.

Fig. 11: Java Class (AppMain.java)

Fig. 11: Java Class (AppMain.java)

3.3.1 Implementation of Model Class

Consider the following POJO class and add the following code to it:

User.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.jcg.hibernate.maven;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "user_table")
public class User {
    @Id
    @Column(name = "user_id")
    private int userid;
    @Column(name = "user_name")
    private String username;
    @Column(name = "created_by")
    private String createdBy;
    @Column(name = "created_date")
    private Date createdDate;
    public int getUserid() {
        return userid;
    }
    public void setUserid(int userid) {
        this.userid = userid;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getCreatedBy() {
        return createdBy;
    }
    public void setCreatedBy(String createdBy) {
        this.createdBy = createdBy;
    }
    public Date getCreatedDate() {
        return createdDate;
    }
    public void setCreatedDate(Date createdDate) {
        this.createdDate = createdDate;
    }
}

3.3.2 Implementation of Utility Class

This class helps in creating the SessionFactory from the Hibernate configuration file and interacts with the database to perform the Hibernate operation. Add the following code to it:

AppMain.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.jcg.hibernate.maven;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class AppMain {
    static User userObj;
    static Session sessionObj;
    static SessionFactory sessionFactoryObj;
    private static SessionFactory buildSessionFactory() {
        // Creating Configuration Instance & Passing Hibernate Configuration File
        Configuration configObj = new Configuration();
        configObj.configure("hibernate.cfg.xml");
        // Since Hibernate Version 4.x, ServiceRegistry Is Being Used
        ServiceRegistry serviceRegistryObj = new StandardServiceRegistryBuilder().applySettings(configObj.getProperties()).build();
        // Creating Hibernate SessionFactory Instance
        sessionFactoryObj = configObj.buildSessionFactory(serviceRegistryObj);
        return sessionFactoryObj;
    }
    public static void main(String[] args) {
        System.out.println(".......Hibernate Maven Example.......\n");
        try {
            sessionObj = buildSessionFactory().openSession();
            sessionObj.beginTransaction();
            for(int i = 101; i <= 105; i++) {
                userObj = new User();
                userObj.setUserid(i);
                userObj.setUsername("Editor " + i);
                userObj.setCreatedBy("Administrator");
                userObj.setCreatedDate(new Date());
                sessionObj.save(userObj);
            }
            System.out.println("\n.......Records Saved Successfully To The Database.......\n");
            // Committing The Transactions To The Database
            sessionObj.getTransaction().commit();
        } catch(Exception sqlException) {
            if(null != sessionObj.getTransaction()) {
                System.out.println("\n.......Transaction Is Being Rolled Back.......");
                sessionObj.getTransaction().rollback();
            }
            sqlException.printStackTrace();
        } finally {
            if(sessionObj != null) {
                sessionObj.close();
            }
        }
    }
}

3.4. Hibernate Configuration File

To configure the Hibernate framework, we need to implement a configuration file i.e. hiberncate.cfg.xml. Right click on src/main/resources folder, New -> Other.

Fig. 12: XML File Creation

Fig. 12: XML File Creation

A new pop window will open and select the wizard as an XML file.

Fig. 13: Wizard Selection

Fig. 13: Wizard Selection

Again, a pop-up window will open. Verify the parent folder location as HibernateMaven/src/main/resources and enter the file name as hibernate.cfg.xml. Click Finish.

Fig. 14: hibernate.cfg.xml

Fig. 14: hibernate.cfg.xml

Once the file is created, we will include the database configuration and mapping classes details. Add the following code to it:

hibernate.cfg.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
<hibernate-configuration>
    <session-factory>
        <!-- SQL Dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- Database Connection Settings -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/tutorialDb</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password"></property>
        <property name="show_sql">true</property>
        <!-- Specifying Session Context -->
        <property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>
        <!-- Mapping With Model Class Containing Annotations -->
        <mapping class="com.jcg.hibernate.maven.User" />
    </session-factory>
</hibernate-configuration>

Notes:

  • Here, we instructed Hibernate to connect to a MySQL database named tutorialDb and the Mapping classes to be loaded
  • We have also instructed Hibernate framework to use MySQLDialect i.e. Hibernate will optimize the generated SQL statements for MySQL
  • This configuration will be used to create a Hibernate SessionFactory object
  • show_sql: This tag will instruct the Hibernate framework to log all the SQL statements on the console

4. Run the Application

To run the Hibernate application, Right click on the AppMain class -> Run As -> Java Application.

Fig. 15: Run Application

Fig. 15: Run Application

5. Project Demo

Executing the AppMain class, you will see the records in user_table table. Developers can debug the example and see what happens in the database after every step. Enjoy!

Fig. 16: Application Output

Fig. 16: Application Output

Below is a snapshot of the MySQL Database after the execution of the above program.

User Table

Fig. 17: User Table Records

Fig. 17: User Table Records

That’s all for this post. Happy Learning!!

6. Conclusion

Hibernate is very useful, it takes plenty of work on itself. The main aim of Hibernate is to make development more easy and convenient. With Maven a basic shell project is ready for Hibernate based development. That’s all for Hibernate Maven tutorial and I hope this article served you whatever you were looking for.