Showing posts with label Coding Tutorial. Show all posts
Showing posts with label Coding Tutorial. Show all posts

Thursday, 13 April 2023

How to Select Collection and delete many documents in the collection using Java? | MongoDB with Java

Mastering Document Deletion: How to Delete Multiple Documents in MongoDB Using Java

🚀 Want to Level Up Your Java Skills?

Join the Ram N Java community for easy-to-follow coding tutorials!

🔔 SUBSCRIBE NOW

Introduction

When managing data in MongoDB with Java, there are often times when you need to clean up your collections by removing more than one record at a time. This tutorial focuses on the deleteMany() method, which allows you to efficiently delete all documents that match a specific filter.

How deleteMany() Works

Unlike deleting a single record, the deleteMany() function looks through your entire collection and removes every single document that meets your criteria. For example, if you want to delete all users who haven't logged in for a year, this is the perfect tool for the job.

Step-by-Step Implementation

  • Step 1: Connect to MongoDB – Establish a connection using the MongoClient and navigate to your specific database and collection.
  • Step 2: Create a Filter – Define the conditions for deletion. You can use fields like "status", "age", or "category" to identify the documents.
  • Step 3: Execute the Delete – Call the collection.deleteMany(filter) method.
  • Step 4: Verify the Result – MongoDB returns a result object that tells you exactly how many documents were successfully deleted.

Key Takeaways for Beginners

Always double-check your filters before running a delete command! If you pass an empty filter, deleteMany() will remove every document in your collection. It's a powerful tool, so use it with care.

Check Out These Related Tutorials

Boost your MongoDB knowledge with these other videos from the channel:

Sunday, 2 April 2023

How to Get and Select a Collection and Insert a Document using Java Program? | MongoDB with Java

🚀 Level Up Your Java Skills!

Subscribe to Ram N Java for high-quality coding and tech tutorials!

✅ SUBSCRIBE NOW

How to Insert a Document into MongoDB Using Java

Adding data to a database is one of the most fundamental tasks for any developer. In this guide, we'll walk through the process of inserting a single document into a MongoDB collection using Java.

Connecting to the Collection

Before you can add data, you must establish a connection to your MongoDB instance. In Java, we use the MongoClient to connect to the server, then select our database and the specific collection where we want to store our information.

Creating the Document

In MongoDB, data is stored as BSON (Binary JSON). In Java, we represent this using the Document class. You can easily add fields like "name", "price", or "category" by using the append() method to build your data structure.

Executing the Insert

Once your document is ready, you simply call the insertOne() method on your collection object. This command sends the document to MongoDB, which then saves it and automatically assigns a unique _id if you haven't provided one.

Thursday, 4 July 2019

How To Configure The Interceptor With Spring Boot Application? | Spring Boot - Interceptor

🚀 Join the Ram N Java Community! 🚀

Get the latest Java and Spring Boot tips delivered straight to your feed.

CLICK TO SUBSCRIBE

Understanding Spring Boot Interceptors

If you have ever wanted to run a piece of code before your request hits the controller or after the response is sent back, you are in the right place! In Spring Boot, this is exactly what Interceptors are for.

What is a Handler Interceptor?

A Handler Interceptor allows you to intercept incoming HTTP requests and outgoing responses. Think of it like a specialized checkpoint that only cares about your application's controllers.

While they might sound similar to Filters, Interceptors are more deeply integrated with Spring's MVC framework, giving you more context about which controller or method is being called.

The Three Key Methods

Interceptors give you three main "hooks" to use:

  • preHandle(): Runs before the controller. You can use this to check things like login status.
  • postHandle(): Runs after the controller finishes, but before the view is rendered.
  • afterCompletion(): Runs after everything is done—perfect for cleaning up or logging performance.

Quick Code Example

To create one, you implement the HandlerInterceptor interface:

@Component
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(...) {
        System.out.println("Pre-Handle logic executed!");
        return true;
    }
}

Explore More Java Tutorials

Expand your knowledge with these related videos from the channel:

Tuesday, 5 March 2019

Spring + JdbcTemplate + How to retrieve auto-generated keys

🚀 Enjoyed the tutorial? Support "Ram N Java" by Subscribing to our YouTube Channel for more Java deep dives!

How to Retrieve Auto-Generated Keys using Spring JdbcTemplate

When working with relational databases, it is very common to have primary keys that are automatically generated (like AUTO_INCREMENT in MySQL or SERIAL in PostgreSQL). After performing an insert operation, you often need that specific ID to use it in subsequent logic.

The Challenge

Normally, a standard update or insert query returns only the number of rows affected. To get the actual key that the database just created, we need a more specialized approach within the Spring framework.

The Solution: GeneratedKeyHolder

Spring JDBC provides a handy interface called KeyHolder and its primary implementation, GeneratedKeyHolder. This object acts as a container for the keys returned by the database.

Step-by-Step Implementation

  1. Create a KeyHolder: Instantiate a new GeneratedKeyHolder().
  2. Use PreparedStatementCreator: Instead of a simple SQL string, you provide a callback that defines how the statement is created and specifies which columns are auto-generated.
  3. Execute the Update: Pass both the PreparedStatementCreator and the KeyHolder to the jdbcTemplate.update() method.
  4. Extract the Key: Access the ID using keyHolder.getKey().

Why is this useful?

This method is cleaner and more reliable than trying to query for the "last inserted ID" manually, which can cause issues in high-traffic environments where multiple users are inserting data at the same time.


Continue Learning

Check out these other Spring JDBC tutorials from the channel:


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

    🌟 Love this tutorial? 🌟

    Join the Ram N Java community for more easy-to-follow Java guides!

    SUBSCRIBE NOW

    How to Create a Database Table using Spring JdbcTemplate

    Creating a table directly from your Java code is a powerful way to manage your database schema, especially during the early stages of development. In this tutorial, we will use Spring JdbcTemplate to execute a Data Definition Language (DDL) statement to create a table.

    1. The "execute" Method

    The JdbcTemplate class provides a method called execute(String sql). This method is typically used for DDL statements like CREATE, DROP, or ALTER. It's the simplest way to run a query that doesn't return data.

    2. Defining the SQL Query

    To create a table, you need a standard SQL query. In our example, we are creating a table named "address" with two columns:

    • ID: To store the unique identifier.
    • CITY: To store the city name.

    3. Spring Configuration

    Before we can run our code, the Spring Container needs to know how to connect to the database. We define a DataSource object in our configuration file with:

    • Driver Class Name
    • Database URL
    • Username and Password

    4. Putting it All Together

    We create a DAO (Data Access Object) class that uses the JdbcTemplate. Once the application context is loaded, we call our create method, and Spring handles the connection and execution for us!

    Pro Tip:

    Always check your database after running the code to verify that the table was created successfully with the correct schema.


    More Spring JDBC Tutorials

    Expand your knowledge with these related videos from my channel:


    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
  • Tuesday, 26 February 2019

    Spring + JdbcTemplate + Update the rows with multiple parameters with object array example

    🚀 Boost Your Java Career!

    Get the latest Spring tutorials delivered straight to your feed. Join Ram N Java today!

    CLICK HERE TO SUBSCRIBE

    Updating Multiple Rows with Object Array in Spring JDBC

    In this guide, we'll explore a powerful way to update records in your database using Spring JdbcTemplate. Specifically, we'll look at how to handle queries with multiple dynamic parameters using an Object[] array.

    The SQL Update Command

    When you need to update a row based on multiple conditions, your SQL uses placeholders (?) for each value. For example, changing an employee's name based on their ID and current age:

    UPDATE employee SET name = ? WHERE age = ? AND id = ?

    Why Use an Object Array?

    Spring's update method is overloaded. While you can pass parameters individually, using an Object Array (new Object[] {param1, param2...}) is highly beneficial because:

    • Cleaner Code: It keeps your method calls organized even with 5 or 10 parameters.
    • Flexibility: It easily handles different data types (String, Integer, etc.) in one go.
    • Readability: It's easy for other developers to see exactly which values correspond to which placeholders.

    Step-by-Step Implementation

    1. Define the SQL: Create a string with your UPDATE statement and ? placeholders.

    2. Prepare the Data: Pack your new values into an Object[]. Make sure the order matches the ? in your SQL!

    3. Call the Method: Use jdbcTemplate.update(sql, objectArray). Spring handles the rest!

    ⚠️ Reminder:

    Always ensure the order of elements in your Object Array matches the order of placeholders in your SQL string to avoid updating the wrong data!

    More from the Spring JDBC Series

    Check out these related videos on Ram N Java to master Spring JDBC:


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

    Click the below Image to Enlarge:
    Spring + JdbcTemplate + Update the rows with multiple parameters with object array example
    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;


    INSERT INTO `employee` (`EMPLOYEE_ID`, `NAME`, `AGE`, `SALARY`) VALUES('1','Peter','28','80000');
    INSERT INTO `employee` (`EMPLOYEE_ID`, `NAME`, `AGE`, `SALARY`) VALUES('2','John','50','40000');
    INSERT INTO `employee` (`EMPLOYEE_ID`, `NAME`, `AGE`, `SALARY`) VALUES('3','David','45','20000');

    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 int updateEmployeeNameBasedOnAge(String name, int age);
    }

    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 int updateEmployeeNameBasedOnAge(String name, int age)
        {
            String sql = "update Employee set Name=? where AGE=?";
            int numberOfRowsAffected = getJdbcTemplate().update(sql,
                    new Object[] { name, age });
            return numberOfRowsAffected;
        }

    }

    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");
            int numberOfRowsAffected = employeeDAO
                    .updateEmployeeNameBasedOnAge("Juli", 28);
            System.out.println("numberOfRowsAffected = " + numberOfRowsAffected);
            System.out.println("Employee name updated successfully.");
        }
    }

    Output:

    Feb 14, 2019 10:42:47 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
    INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@35d176f7: startup date [Thu Feb 14 10:42:47 IST 2019]; root of context hierarchy
    Feb 14, 2019 10:42:47 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 14, 2019 10:42:48 AM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
    INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
    Thu Feb 14 10:42:57 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.
    numberOfRowsAffected = 1
    Employee name updated successfully.

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

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

    Bitbucket Link:
    https://bitbucket.org/ramram43210/java_spring_2019/src/8f8b5563b7f2921ed260908e4906103995d9c6cc/Spring_2019/SpringDemo_update_object_array/?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