Showing posts with label JdbcTemplate. Show all posts
Showing posts with label JdbcTemplate. Show all posts

Saturday, 1 February 2020

How to delete an employee using Spring boot layered architecture and JdbcTemplate?

Master Your Java Skills!

Join the Ram N Java family for high-quality coding tutorials and professional tips.

SUBSCRIBE NOW

Understanding the Deletion Process in Spring Boot

Deleting a record from a database might seem simple, but in a professional Spring Boot application, it requires a clean, structured approach. This ensures that your application remains scalable, maintainable, and bug-free. In this tutorial, we focus on the "Delete" part of the CRUD operations using JdbcTemplate.

The Power of Layered Architecture

When we build enterprise applications, we don't just write all the code in one place. We use a Layered Architecture:

  • Controller Layer: Handles the incoming web requests.
  • Service Layer: Contains the business logic (e.g., "Can this employee be deleted?").
  • Repository Layer: Communicates directly with the database using JdbcTemplate.

Using JdbcTemplate for Deletion

The JdbcTemplate.update() method is our primary tool here. It allows us to execute SQL DELETE statements safely using prepared statements, which protects our application from SQL injection attacks.

🚀 Pro Tip:

Always check the "rows affected" count returned by the update method. If it returns 0, it means the ID you tried to delete doesn't exist in the database!

Key Takeaways

By following this layered approach, you ensure that your code is easy to test and modify later. Watch the full video above to see the step-by-step implementation and how we connect all these layers together seamlessly!

How to get all employees using Spring boot layered architecture and JdbcTemplate?

Level Up Your Java Skills!

Join the Ram N Java community for high-quality Spring Boot tutorials and expert coding tips.

SUBSCRIBE NOW

Mastering Database Reads in Spring Boot

Fetching data is one of the most common tasks in any application. In this tutorial, we explore how to retrieve all employee records from a database using JdbcTemplate while maintaining a clean Layered Architecture. This approach ensures your code is organized and professional.

The Power of JdbcTemplate

Spring's JdbcTemplate simplifies database interactions by handling the boring parts—like opening connections and closing statements—so you can focus on writing your SQL. It’s a great way to stay close to SQL while enjoying the benefits of the Spring framework.

Why Layered Architecture?

  • Separation of Concerns: Each part of your app has one job.
  • Maintainability: Easy to find and fix bugs.
  • Scalability: Adding new features becomes much simpler.

How it Works Step-by-Step

We start by defining an Employee model. Then, we use the query() method from JdbcTemplate along with a RowMapper to transform database rows into Java objects effortlessly.

💡 Key Insight for Beginners:

The RowMapper is the bridge between your database and your Java code. It tells Spring exactly how to map columns (like 'id' or 'name') to your Employee object's fields.

Conclusion

By using JdbcTemplate with a layered structure, you're building a foundation for enterprise-grade applications. Watch the full video above to see the complete implementation and code walkthrough!

How to get an employee using Spring boot layered architecture and JdbcTemplate?

🚀 Loved this tutorial? Subscribe to Ram N Java for more easy-to-follow coding guides! 🌟

Understanding Layered Architecture in Spring Boot

In this tutorial, we dive into how to retrieve employee records from a database using Spring Boot and JdbcTemplate. The key to building professional applications is a "Layered Architecture," which keeps your code clean and organized. We break it down into three simple parts:

  • Controller Layer: This is the entry point that handles incoming requests (like from Postman).
  • Service Layer: This is where the business logic lives, acting as a bridge between the controller and the data.
  • Repository Layer: This layer talks directly to your database (MySQL) to fetch the actual data.

Step-by-Step Implementation

1. Configuration & Database

We start by setting up our application.properties with the database URL, username, and password. This allows Spring Boot to establish a connection to your MySQL server automatically.

2. The Employee Model

We create a simple Java class called Employee with properties like ID, Name, Age, and Salary. We include getters, setters, and a toString method to make the data easy to work with.

3. Using JdbcTemplate & RowMapper

The JdbcTemplate is a powerful tool that simplifies database operations. We use the queryForObject method to execute a SQL SELECT statement. To map the database rows to our Java Employee object, we implement the RowMapper interface.

4. Testing with Postman

Once the layers are connected, we run the Spring Boot application and use Postman to send a GET request. You'll see the flow of data from the Controller, through the Service, into the Repository, and finally back to you as a clean JSON response!

Watch More Tutorials

Check out these other helpful videos from my channel:

How to update an employee using Spring boot layered architecture and JdbcTemplate?

🚀 Want to master Spring Boot? Subscribe to Ram N Java for more expert coding tutorials! 🌟

Updating Data with Spring Boot & JdbcTemplate

In our previous tutorials, we learned how to retrieve data. Today, we're taking it a step further by learning how to Update records in a MySQL database using Spring Boot and JdbcTemplate. We will continue following the professional Layered Architecture to ensure our code is scalable and easy to maintain.

The Core Concept: Layered Architecture

To keep things simple for beginners, remember that every request flows through these sections:

  • Controller: Handles the web request (the "brain" that receives instructions).
  • Service: Handles the business logic (the "logic" that decides what to do).
  • Repository: Handles the database communication (the "muscles" that do the heavy lifting).

Step-by-Step Implementation

1. Creating the Update Repository Method

In the Repository layer, we use the jdbcTemplate.update() method. This method is used for all "Data Manipulation Language" (DML) operations like INSERT, UPDATE, and DELETE. We write a standard SQL query: UPDATE employee SET name = ?, age = ? WHERE id = ?.

2. Connecting via the Service Layer

The Service layer acts as the middleman. It receives the updated data from the controller and passes it down to the repository. This is where you would typically add any validation or extra logic before saving the data.

3. Exposing the PUT Endpoint

In the Controller, we use the @PutMapping annotation. This tells Spring Boot that this method should handle HTTP PUT requests, which are standard for updating existing resources.

4. Testing with Postman

Once everything is coded, we jump into Postman. We send a JSON body with the new details for an existing employee ID. If everything is correct, the database updates instantly, and we receive a success confirmation!

Explore More Coding Tutorials

Expand your knowledge with these related videos from my channel:

Friday, 17 January 2020

How to create an employee using Spring boot layered architecture and JdbcTemplate?

🚀 Ready to Level Up Your Coding Skills?
Click here to Subscribe to Ram N Java! 🌟 Join our community for more easy-to-understand tutorials!

Mastering Data Creation in Spring Boot

In this tutorial, we explore the fundamental process of adding new data to a database using Spring Boot and JdbcTemplate. Creating records is the first step in any CRUD application, and doing it the right way using Layered Architecture makes your code professional, clean, and extremely easy to debug.

The Power of Layered Architecture

We organize our application into three distinct layers to ensure every part has a specific job:

  • Controller Layer: Receives the data from the user (usually as JSON) via a POST request.
  • Service Layer: Validates the data and coordinates the flow between the controller and the database.
  • Repository Layer: Uses JdbcTemplate to talk to MySQL and save the record securely.

Key Steps in the Tutorial

1. Handling POST Requests

We use the @PostMapping annotation in our Controller. This setup allows the application to accept data sent through the request body, which is the standard way to create new resources in REST APIs.

2. Implementing the Save Method

In the Repository, we utilize the jdbcTemplate.update() method. By passing an SQL INSERT statement and the values from our Employee object, Spring Boot handles the heavy lifting of database connectivity for us.

3. Testing with Postman

Testing is crucial! We walk through how to use Postman to send a JSON payload representing a new employee. You'll see how the application processes the request and returns a successful status once the data is safely stored in MySQL.

Explore More from Ram N Java

Keep learning with these randomly selected tutorials from our channel:

Friday, 3 January 2020

How to delete the record from the database using JdbcTemplate with Spring Boot? | Spring Boot

🚀 Level Up Your Coding Skills!

Subscribe to Ram N Java for more easy-to-follow Spring Boot and Java tutorials!

Click Here to SUBSCRIBE!

Effortlessly Delete Data in Spring Boot with JdbcTemplate

Deleting data is a fundamental part of any application's CRUD (Create, Read, Update, Delete) operations. In this guide, we dive deep into how you can use Spring Boot's JdbcTemplate to remove records from your database safely and efficiently.

Why Use JdbcTemplate for Deletion?

While JPA is popular, JdbcTemplate offers more control and better performance for simple SQL operations. It handles the connection management and cleanup for you, allowing you to focus on the logic.

The Core Method: update()

To delete a record, we use the update method. Despite its name, it is the standard way to execute DELETE and UPDATE queries in Spring JDBC. It returns the number of rows affected, which is great for verifying if the deletion actually happened.

Step-by-Step Implementation

  • Write the SQL: Create a query like "DELETE FROM users WHERE id = ?".
  • Pass Parameters: Use the ID or any unique field to target the specific row.
  • Execute: Use jdbcTemplate.update(sql, id) to run the command.

Real-World Example

Imagine an e-commerce app where a user wants to remove an item from their cart. You would use JdbcTemplate to find that item by its Product ID and delete it from the database in real-time!

Check Out More From My Channel

If you found this useful, here are three other videos you might enjoy:

How to update the record in the database using JdbcTemplate with Spring Boot? | Spring Boot Tutorial

🚀 Level Up Your Java Career!

Subscribe to Ram N Java for the most simplified Spring Boot and Java tutorials on YouTube!

Click Here to SUBSCRIBE!

Mastering Database Updates in Spring Boot

Updating existing records is a core part of any application. Whether it's changing a user's email or updating an order status, you need a reliable way to handle these changes. In this guide, we explore how Spring Boot's JdbcTemplate makes database updates simple and efficient.

Why JdbcTemplate for Updates?

JdbcTemplate is a powerful tool because it removes the boilerplate code of traditional JDBC. It handles opening and closing connections, so you only have to focus on your SQL and the data you want to change.

The Key Method: update()

In Spring JDBC, the update() method is the "Swiss Army Knife" for data modification. You use it for INSERT, UPDATE, and DELETE operations. It returns an integer representing the number of rows affected—perfect for knowing if your update was successful.

Practical Implementation Steps

  • SQL Query: Use a standard SQL string like "UPDATE employees SET name = ? WHERE id = ?".
  • Parameter Mapping: Pass the values you want to change in the order they appear in the query.
  • Execution: Call jdbcTemplate.update(sql, newName, id) to push the changes to the database.

A Real-World Example

Think about a profile settings page. When a user updates their display name, the backend receives that request and uses a JdbcTemplate update command to modify that specific row in the database instantly!

More Tech Tutorials from Ram N Java

Expand your knowledge with these related videos:

How to get all records from the database using JdbcTemplate with Spring Boot? | Spring Boot Tutorial

🚀 Level Up Your Java Career!

Subscribe to Ram N Java for the most simplified Spring Boot and Java tutorials on YouTube!

Click Here to SUBSCRIBE!

Mastering Database Fetching in Spring Boot

Retrieving data is the most common task in any application. Whether you're building a dashboard or a simple list view, you need to know how to pull all records from your database. In this guide, we dive into how Spring Boot's JdbcTemplate makes fetching list data simple and efficient.

What is JdbcTemplate Querying?

JdbcTemplate provides several methods to retrieve data. While some methods fetch a single record, the query() method is specifically designed to handle multiple rows, returning them as a List of objects that your application can easily use.

The Power of RowMapper

The secret to fetching multiple records is the RowMapper. This interface tells Spring how to map each row from the database result set into a Java object. It’s like a bridge between your SQL tables and your Java code.

Step-by-Step Implementation

  • Write the SQL: Use a simple query like "SELECT * FROM employees".
  • Create a Mapper: Define how each column maps to your class fields.
  • Execute & Collect: Use jdbcTemplate.query(sql, mapper) to get your full list of data.

Why Choose This Approach?

Using JdbcTemplate for fetching records gives you maximum performance. Unlike heavy ORMs, it executes direct SQL, making it ideal for applications where speed and low memory usage are critical.

More Tech Tutorials from Ram N Java

Check out these other helpful videos to boost your coding skills:

How to get a record from the database using JdbcTemplate with Spring Boot? | Spring Boot Tutorial

🚀 Level Up Your Java Career!

Subscribe to Ram N Java for the most simplified Spring Boot and Java tutorials on YouTube!

Click Here to SUBSCRIBE!

Mastering Database Fetching in Spring Boot

When building a backend application, fetching data efficiently is one of the most critical skills you can have. In this guide, we dive deep into how Spring Boot's JdbcTemplate allows you to retrieve records from your database with minimal code and maximum performance.

What is JdbcTemplate?

JdbcTemplate is the core class in the Spring JDBC framework. It handles the low-level details like opening/closing connections and preparing statements, leaving you to focus on the SQL logic and how to handle the results.

Fetching a Single Record

Sometimes you only need one specific piece of data—like a user profile based on an ID. We use the queryForObject() method for this. It takes your SQL query, the arguments, and a RowMapper to transform that database row into a Java object.

Understanding the RowMapper

The RowMapper is the bridge between your SQL world and your Java world. It tells Spring exactly which database column corresponds to which field in your Java class. It’s simple, powerful, and very clean!

Why Use This Over JPA?

While Hibernate and JPA are great, JdbcTemplate gives you total control over the SQL. It’s faster for simple queries and much easier to debug because you see exactly what SQL is being sent to the database.

More From Ram N Java

Check out these other helpful tutorials to boost your skills:

How to insert a record in the database using JdbcTemplate with Spring Boot? | Spring Boot Tutorial

🚀 Master Spring Boot Today!

Subscribe to Ram N Java for the most simplified and professional Java tutorials on YouTube!

Click Here to SUBSCRIBE!

Mastering Database Inserts in Spring Boot

Adding data to a database is one of the first things you'll do in any application. Whether it's a new user signing up or saving a new product, you need a method that is both simple and reliable. In this guide, we'll show you how Spring Boot's JdbcTemplate makes inserting data completely effortless.

What is JdbcTemplate?

JdbcTemplate is a powerful tool provided by Spring that simplifies the way we talk to databases. It handles the "boring" stuff like managing connections and cleanup, so you can focus purely on your SQL and your application's logic.

The Magic Method: update()

In Spring JDBC, we use the update() method for inserting records. While it sounds like it's only for changing existing data, it is actually the standard way to run any INSERT, UPDATE, or DELETE command. It even tells you how many rows were added!

3 Steps to Insert Data

  • The Query: Write your standard SQL insert like "INSERT INTO users (name, email) VALUES (?, ?)".
  • The Parameters: Pass the actual values you want to save in place of the question marks.
  • The Execution: Call the update method and watch your data get saved instantly!

Practical Benefits

Using JdbcTemplate is often faster and uses less memory than heavy frameworks. It's the perfect choice when you want high performance and want to keep your code readable and easy to maintain.

Boost Your Skills with More Videos

Check out these other helpful tutorials from Ram N Java:

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
  • Tutorials