Friday, 29 March 2019

Java.util.Random class Introduction | How to generate Random numbers? - Playlist

Java.util.Random class Introduction | How to generate Random numbers?

https://www.youtube.com/watch?v=kCLbOkhl2-w

Spring 4 + Hibernate 4 + MySQL 8 + Maven Integration example using XML Configuration

🚀 Level Up Your Java Skills!

Subscribe to Ram N Java for easy-to-understand tutorials on Spring, Hibernate, and more!

CLICK HERE TO SUBSCRIBE

Mastering Spring 4 and Hibernate 4 Integration

Integrating powerful frameworks like Spring and Hibernate is a core skill for any Java developer. In this guide, we walk through a complete example of how to connect these frameworks using MySQL 8 and Maven with a classic XML-based configuration.

1. Why XML Configuration?

While annotations are popular, understanding XML configuration is essential for maintaining legacy systems and understanding how the "magic" happens behind the scenes. It provides a clear, centralized place to manage your beans and database settings.

2. The Role of Maven

Maven acts as your project manager. Instead of manually searching for JAR files, we define our dependencies in the pom.xml. This ensures that Spring, Hibernate, and the MySQL connector all work together seamlessly.

3. Setting Up MySQL 8

MySQL 8 introduced new security and performance features. We'll show you the exact properties you need in your configuration to ensure a stable connection between your Java application and the database.

Key Takeaways for Beginners:

  • How to structure a Maven project.
  • Defining DataSources and SessionFactories in XML.
  • Performing basic CRUD operations.

Spring 4 + Hibernate 4 + MySQL 8 + Maven Integration example using Annotations Configuration

🚀 Master Java Development with Us!

Enjoyed this tutorial? Don't miss out on more deep dives into Spring and Hibernate.

SUBSCRIBE TO RAM N JAVA

Spring 4 and Hibernate 4 Integration Guide

Welcome! In this tutorial, we explore how to integrate Spring 4 with Hibernate 4 using MySQL 8 and Maven. This guide is perfect for beginners who want to understand how these technologies work together using modern annotation-based configurations.

1. Setting Up Your Database

First, we start with a simple Employee table. This table includes essential columns such as:

  • ID: Unique identifier
  • Name: Employee name
  • Joining Date: When the employee started
  • Salary: Compensation details
  • SSN: Social Security Number for identification

2. Project Structure & Dependencies

Using Maven, we manage all necessary dependencies in the pom.xml file. A critical tip: Always ensure your MySQL Connector version is compatible with the MySQL server installed on your machine to avoid connection issues.

3. Configuration Classes

We move away from bulky XML files and use Java Annotations. We create a HibernateConfiguration class where we define:

  • DataSource: Contains the URL, username, and password for your database.
  • SessionFactory: Manages Hibernate sessions.
  • TransactionManager: Handles database transactions smoothly.

4. Performing CRUD Operations

In the tutorial, we demonstrate how to perform the core database actions (CRUD):

  • Create: Saving a new employee record.
  • Read: Fetching all employees or searching by SSN.
  • Update: Modifying existing data (like changing a salary).
  • Delete: Removing records from the table.

Watch and Learn More

Check out these other helpful videos from Ram N Java to keep growing your skills:

Sunday, 24 March 2019

What is HibernateTransactionManager in Spring ?


 


Click the below link to watch on Youtube:
https://www.youtube.com/watch?v=eVImYjYD5_E

Spring hibernate integration - Playlist

Spring 3 + hibernate 3 + Maven integration example

🔥 Level Up Your Coding Skills!

Join thousands of developers on Ram N Java. Get the latest tutorials delivered to you!

SUBSCRIBE TO RAM N JAVA

Mastering Spring 3 and Hibernate 3 Integration

Are you looking to build robust Java applications? Integrating Spring 3 with Hibernate 3 is a classic yet powerful approach. In this comprehensive guide, we walk through a complete integration example using Maven to manage your dependencies.

Why Use Spring with Hibernate?

Spring provides excellent support for Hibernate by handling the boilerplate code. It manages the session factory, transaction management, and simplifies data access through the DAO pattern.

Key Components of the Project

In the video, we cover several critical areas for a successful setup:

  • Maven Project Structure: How to organize your folders and source files.
  • The pom.xml File: Adding dependencies for Spring Core, Spring ORM, Hibernate, and the MySQL Connector.
  • Application Context: Configuring the DataSource, SessionFactory, and Transaction Manager in XML.
  • Entity Mapping: Mapping your Java classes to database tables using Hibernate XML mappings.

Step-by-Step Implementation

We start by creating a simple Employee model. From there, we build the DAO (Data Access Object) layer to handle database interaction. You will see how the HibernateTemplate or SessionFactory makes database queries clean and efficient.

Check Out These Other Videos

Enjoyed this tutorial? You might also find these videos from my channel helpful:

Sunday, 10 March 2019

Spring - How to get all records by calling the stored procedure using SimpleJdbcCall

Spring - Calling a stored function using SimpleJdbcCall | Spring JDBC tutorial | Spring JDBC

Spring - Calling a stored procedure with SimpleJdbcCall (Explicitly declaring parameters)

Spring - Calling a stored procedure with SimpleJdbcCall | Spring JDBC tutorial

Spring - Inserting data using SimpleJdbcInsert and MapSqlParameterSource | Spring JDBC tutorial

Spring - Inserting data using SimpleJdbcInsert and SqlParameterSource | Spring JDBC tutorial

Tuesday, 5 March 2019

How to use format(Locale l, String format, Object... args) method of java.util.Formatter class


Click here to watch on Youtube:
https://www.youtube.com/watch?v=ec2-YfmtPSk&list=UUhwKlOVR041tngjerWxVccw

FormatterDemo.java

import java.util.Formatter;
import java.util.Locale;

/**
 * public Formatter format(Locale l, String format, Object... args)
 *
 * Parameters:
 *
 * l - The locale to apply during formatting.
 *
 * format - A format string as described in Format string syntax.
 *
 * args - Arguments referenced by the format specifiers in the format
 * string. If there are more arguments than format specifiers, the
 * extra arguments are ignored. The maximum number of arguments is
 * limited by the maximum dimension of a Java array as defined by The
 * Java™ Virtual Machine Specification.
 *
 * Returns: This formatter
 *
 */

public class FormatterDemo
{

    public static void main(String[] args)
    {
        Formatter formatter = new Formatter();

        /*
         * In this example, the format specifiers, %s and %d are
         * replaced with the arguments that follow the format string.
         * %s is replaced by "Peter", %d is replaced by 10. %s
         * specifies a string, and %d specifies an integer value. All
         * other characters are simply used as-is.
         */

        formatter.format(Locale.US, "%s age is %d", "Peter", 10);
        System.out.println(formatter.out());
        formatter.close();
    }

}

Output:

Peter age is 10

Click the below link to download the code:
https://sites.google.com/site/javaspringram2019/java_spring_2019/FormatterDemo_format_locale.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java_Spring_2019/tree/master/Java_2019/FormatterDemo_format_locale

Bitbucket Link:
https://bitbucket.org/ramram43210/java_spring_2019/src/ef6f73b2185c28cb9cd0149bcd1e9fa0a5b2bdf3/Java_2019/FormatterDemo_format_locale/?at=master

See also:

  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Spring Tutorial
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Cooking Tutorial
  • How to format the string using java.util.Formatter class


    Click here to watch on Youtube:
    https://www.youtube.com/watch?v=qt89kDYMBGo&list=UUhwKlOVR041tngjerWxVccw

    Click the below Image to Enlarge:

    How to format the string using java.util.Formatter class

    FormatterDemo.java

    import java.util.Formatter;

    /**
     * public Formatter format(String format, Object... args)
     *
     * Parameters:
     *
     * format - A format string as described in Format string syntax.
     *
     * args - Arguments referenced by the format specifiers in the format
     * string. If there are more arguments than format specifiers, the
     * extra arguments are ignored. The maximum number of arguments is
     * limited by the maximum dimension of a Java array as defined by The
     * Java™ Virtual Machine Specification.
     *
     * Returns: This formatter
     *
     */

    public class FormatterDemo
    {

        public static void main(String[] args)
        {
            Formatter formatter = new Formatter();

            /*
             * In this example, the format specifiers, %s and %d are
             * replaced with the arguments that follow the format string.
             * %s is replaced by "Peter", %d is replaced by 10. %s
             * specifies a string, and %d specifies an integer value. All
             * other characters are simply used as-is.
             */

            formatter.format("%s age is %d", "Peter", 10);
            System.out.println(formatter.out());
            formatter.close();
        }

    }

    Output:

    Peter age is 10

    Refer: 
    https://docs.oracle.com/javase/8/docs/api/index.html?java/util/Formatter.html

    Click the below link to download the code:
    https://sites.google.com/site/javaspringram2019/java_spring_2019/FormatterDemo_Intro.zip?attredirects=0&d=1

    Github Link:
    https://github.com/ramram43210/Java_Spring_2019/tree/master/Java_2019/FormatterDemo_Intro

    Bitbucket Link:
    https://bitbucket.org/ramram43210/java_spring_2019/src/ef6f73b2185c28cb9cd0149bcd1e9fa0a5b2bdf3/Java_2019/FormatterDemo_Intro/?at=master

    See also:

  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Spring Tutorial
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Cooking Tutorial
  • Spring + JdbcTemplate + How to retrieve auto-generated keys


    Click here to watch on Youtube:
    https://www.youtube.com/watch?v=rbi3TkO0q5U&list=UUhwKlOVR041tngjerWxVccw

    Click the below Image to Enlarge:

    Spring + JdbcTemplate + How to retrieve auto-generated keys

    Employee.sql

    CREATE DATABASE org_db;


    CREATE TABLE `employee` (
      `EMPLOYEE_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
      `NAME` VARCHAR(100) NOT NULL,
      `AGE` INT(10) NOT NULL,
      `SALARY` INT(10) DEFAULT NULL,
      PRIMARY KEY (`EMPLOYEE_ID`)
    ) ENGINE=INNODB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

    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/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.ram.core</groupId>
        <artifactId>SpringDemo</artifactId>
        <packaging>jar</packaging>
        <version>1.0-SNAPSHOT</version>
        <name>SpringDemo</name>
        <url>http://maven.apache.org</url>

        <properties>
            <spring.version>5.0.5.RELEASE</spring.version>
        </properties>

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

            <!-- Spring 5 dependencies -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${spring.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>

            <!-- MySQL database driver -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.11</version>
            </dependency>

        </dependencies>

    </project>

    EmployeeDAO.java

    package com.ram.employee.dao;

    public interface EmployeeDAO
    {
        public void retriveAutoGeneratedKey();
    }

    EmployeeDAOImpl.java

    package com.ram.employee.dao.impl;

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

    import org.springframework.jdbc.core.PreparedStatementCreator;
    import org.springframework.jdbc.core.support.JdbcDaoSupport;
    import org.springframework.jdbc.support.GeneratedKeyHolder;
    import org.springframework.jdbc.support.KeyHolder;

    import com.ram.employee.dao.EmployeeDAO;

    public class EmployeeDAOImpl
            extends JdbcDaoSupport implements EmployeeDAO
    {

        public void retriveAutoGeneratedKey()
        {
            final String INSERT_SQL = "INSERT INTO EMPLOYEE "
                    + "(NAME, AGE,SALARY) VALUES (?, ?, ?)";

            KeyHolder keyHolder = new GeneratedKeyHolder();
            getJdbcTemplate().update(new PreparedStatementCreator()
            {
                public PreparedStatement createPreparedStatement(
                        Connection connection) throws SQLException
                {
                    PreparedStatement ps = connection.prepareStatement(
                            INSERT_SQL, new String[] { "id" });
                    ps.setString(1, "Rob");
                    ps.setInt(2, 12);
                    ps.setInt(3, 9090);
                    return ps;
                }
            }, keyHolder);

            System.out.println(
                    "Auto generated Key is = " + keyHolder.getKey());
        }

    }

    applicationContext.xml

    <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-4.3.xsd">


        <bean id="dataSource"
            class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver" />
            <property name="url" value="jdbc:mysql://localhost:3306/org_db" />
            <property name="username" value="root" />
            <property name="password" value="root" />
        </bean>

        <bean id="employeeDAO" class="com.ram.employee.dao.impl.EmployeeDAOImpl">
            <property name="dataSource" ref="dataSource" />
        </bean>
     
    </beans>

    App.java

    package com.ram.core;

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

    import com.ram.employee.dao.EmployeeDAO;

    public class App
    {
        public static void main(String[] args)
        {
            ApplicationContext context = new ClassPathXmlApplicationContext(
                    "applicationContext.xml");

            EmployeeDAO employeeDAO = (EmployeeDAO) context
                    .getBean("employeeDAO");
            employeeDAO.retriveAutoGeneratedKey();
        }
    }

    Output:

    Feb 20, 2019 10:36:51 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
    INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@736e9adb: startup date [Wed Feb 20 10:36:51 IST 2019]; root of context hierarchy
    Feb 20, 2019 10:36:52 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
    INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
    Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
    Feb 20, 2019 10:36:52 AM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
    INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
    Wed Feb 20 10:36:53 IST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
    Auto generated Key is = 10

    Click the below link to download the code:
    https://sites.google.com/site/javaspringram2019/java_spring_2019/SpringDemo_Retrive_auto_key.zip?attredirects=0&d=1

    Github Link:
    https://github.com/ramram43210/Java_Spring_2019/tree/master/Spring_2019/SpringDemo_Retrive_auto_key

    Bitbucket Link:
    https://bitbucket.org/ramram43210/java_spring_2019/src/8f8b5563b7f2921ed260908e4906103995d9c6cc/Spring_2019/SpringDemo_Retrive_auto_key/?at=master

    See also:

  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Spring Tutorial
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Cooking Tutorial
  • Spring + JdbcTemplate + How to create a table


    Click here to watch on Youtube:
    https://www.youtube.com/watch?v=S2EyOdg7dZM&list=UUhwKlOVR041tngjerWxVccw

    Click the below Image to Enlarge:

    Spring + JdbcTemplate + How to create a table

    Employee.sql

    CREATE DATABASE org_db;


    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/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.ram.core</groupId>
        <artifactId>SpringDemo</artifactId>
        <packaging>jar</packaging>
        <version>1.0-SNAPSHOT</version>
        <name>SpringDemo</name>
        <url>http://maven.apache.org</url>

        <properties>
            <spring.version>5.0.5.RELEASE</spring.version>
        </properties>

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

            <!-- Spring 5 dependencies -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${spring.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>

            <!-- MySQL database driver -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.11</version>
            </dependency>

        </dependencies>

    </project>

    EmployeeDAO.java

    package com.ram.employee.dao;

    public interface EmployeeDAO
    {
        public void createTable();
    }

    EmployeeDAOImpl.java

    package com.ram.employee.dao.impl;

    import org.springframework.jdbc.core.support.JdbcDaoSupport;

    import com.ram.employee.dao.EmployeeDAO;

    public class EmployeeDAOImpl
            extends JdbcDaoSupport implements EmployeeDAO
    {

        public void createTable()
        {
            String sql = "create table Address (id integer, city varchar(100))";
            getJdbcTemplate().execute(sql);
        }

    }

    applicationContext.xml

    <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-4.3.xsd">


        <bean id="dataSource"
            class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver" />
            <property name="url" value="jdbc:mysql://localhost:3306/org_db" />
            <property name="username" value="root" />
            <property name="password" value="root" />
        </bean>

        <bean id="employeeDAO" class="com.ram.employee.dao.impl.EmployeeDAOImpl">
            <property name="dataSource" ref="dataSource" />
        </bean>
     
    </beans>

    App.java

    package com.ram.core;

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

    import com.ram.employee.dao.EmployeeDAO;

    public class App
    {
        public static void main(String[] args)
        {
            ApplicationContext context = new ClassPathXmlApplicationContext(
                    "applicationContext.xml");

            EmployeeDAO employeeDAO = (EmployeeDAO) context
                    .getBean("employeeDAO");
            employeeDAO.createTable();
            System.out.println("Table is created successfully.");
        }
    }

    Output:

    Feb 20, 2019 9:52:03 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
    INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@35d176f7: startup date [Wed Feb 20 09:52:03 IST 2019]; root of context hierarchy
    Feb 20, 2019 9:52:04 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
    INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
    Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
    Feb 20, 2019 9:52:05 AM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
    INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
    Wed Feb 20 09:52:16 IST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
    Table is created successfully.

    Click the below link to download the code:
    https://sites.google.com/site/javaspringram2019/java_spring_2019/SpringDemo_create_table.zip?attredirects=0&d=1

    Github Link:
    https://github.com/ramram43210/Java_Spring_2019/tree/master/Spring_2019/SpringDemo_create_table

    Bitbucket Link:
    https://bitbucket.org/ramram43210/java_spring_2019/src/8f8b5563b7f2921ed260908e4906103995d9c6cc/Spring_2019/SpringDemo_create_table/?at=master

    See also:

  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Spring Tutorial
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Cooking Tutorial
  • Tutorials