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:

Sunday, 10 March 2019

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

🚀 Want to Master Spring & Java Development?

Subscribe to Ram N Java for beginner-friendly coding tutorials and practical guides!

🔔 Subscribe to YouTube Channel

Calling Stored Procedures with SimpleJdbcCall in Spring JDBC

Executing database stored procedures in standard JDBC traditionally involves configuring verbose CallableStatement instances, registering OUT parameters manually, and handling raw SQL strings. Spring JDBC provides SimpleJdbcCall, a multi-threaded, metadata-aware class designed to simplify calling stored procedures and database functions with minimal configuration.

1. What is SimpleJdbcCall?

SimpleJdbcCall is part of the org.springframework.jdbc.core.simple package. It automatically reads database metadata to inspect parameter names, types, and directions (IN, OUT, and INOUT):

  • Automatic Parameter Detection: Discovers procedure signature parameters from the database catalog, reducing manual registration.
  • Zero Boilerplate: Eliminates explicit SQL execution queries like {call procedure_name(?, ?)}.
  • Result Mapping: Easily captures returned scalar values, output parameter maps, or multiple ResultSet rows using RowMappers.

2. How to Configure SimpleJdbcCall

To set up SimpleJdbcCall inside your DAO or repository layer:

  • Instantiate with DataSource or JdbcTemplate: Initialize the instance by passing your configured DataSource or JdbcTemplate bean.
  • Declare the Procedure Name: Call withProcedureName("procedure_name") to specify the target procedure.
  • Register Out Parameters (Optional): If the database metadata does not supply return definitions, declare parameters explicitly with declareParameters(...).
  • Compile the Call: The configuration compiles automatically on the first call, making subsequent invocations fast and thread-safe.

3. Passing IN Parameters and Retrieving OUT Results

Invoking the procedure and obtaining results is straightforward:

  • Supplying Parameters: Use MapSqlParameterSource to add IN parameters by chaining .addValue("paramName", value).
  • Executing the Call: Call simpleJdbcCall.execute(paramSource), which returns a Map<String, Object> containing all OUT parameter values indexed by parameter name.
  • Accessing Outputs: Retrieve values cleanly from the map using the corresponding output parameter name key.

4. Key Advantages

Using SimpleJdbcCall provides significant improvements over low-level JDBC approaches:

  • Cleaner DAO Layer: Cuts out dozens of lines of repetitive setup code.
  • Thread Safety: Configure once during bean initialization and safely reuse across multiple concurrent requests.
  • Fewer Runtime Bugs: Eliminates mismatched index positions and incorrect SQL type registrations.

📺 Explore More Spring JDBC Tutorials

Continue expanding your Java and Spring knowledge with these related tutorials from our channel:

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

🚀 Want to Master Spring & Java Development?

Subscribe to Ram N Java for beginner-friendly coding tutorials and practical guides!

🔔 Subscribe to YouTube Channel

Efficient Data Insertion: SimpleJdbcInsert with MapSqlParameterSource

In Spring JDBC, SimpleJdbcInsert streamlines database write operations by reading table metadata directly and eliminating the need for boilerplate INSERT INTO SQL statements. When coupled with MapSqlParameterSource, mapping input parameters becomes structured, highly readable, and type-safe.

1. Why Use MapSqlParameterSource?

While SimpleJdbcInsert can accept standard Java Map objects, MapSqlParameterSource provides key benefits tailored for JDBC operations:

  • Fluent Method Chaining: Add multiple parameters cleanly using chained .addValue("columnName", value) calls.
  • Explicit SQL Type Specification: Supports explicit SQL types (e.g., Types.VARCHAR, Types.INTEGER) when inserting null or custom values.
  • Spring-Native Integration: Implements the SqlParameterSource interface natively, allowing seamless interoperability across Spring JDBC components.

2. Setting Up SimpleJdbcInsert

Configuring SimpleJdbcInsert in your data access layer is quick and clean:

  • Instantiate with DataSource: Initialize the instance by passing your configured DataSource bean.
  • Set Table Name: Use withTableName("table_name") to specify the target database table.
  • Restrict Columns (Optional): Optionally define specific columns using usingColumns(...) to let database defaults handle the rest.
  • Generated Keys: Use usingGeneratedKeyColumns(...) if your table features auto-increment primary keys.

3. Executing Inserts with MapSqlParameterSource

Executing the insert takes just two concise steps:

  • Build the Parameters: Instantiate new MapSqlParameterSource() and chain .addValue("column", value) for each database field.
  • Execute the Statement: Call simpleJdbcInsert.execute(paramSource) or executeAndReturnKey(paramSource) to run the insert and retrieve generated identifiers.

4. Key Takeaways

Using MapSqlParameterSource with SimpleJdbcInsert prevents common syntax mistakes, eliminates positional parameter bugs, and keeps your DAO implementation concise and easy to maintain.

📺 Explore More Spring JDBC Tutorials

Continue expanding your Java and Spring knowledge with these related tutorials from our channel:

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

🚀 Want to Master Spring & Java Development?

Subscribe to Ram N Java for beginner-friendly coding tutorials and practical guides!

🔔 Subscribe to YouTube Channel

Inserting Data with SimpleJdbcInsert and SqlParameterSource

When working with database persistence in Spring applications, SimpleJdbcInsert provides a clean way to insert records without writing repetitive SQL queries. Pairing it with the SqlParameterSource interface makes parameter binding structured, type-safe, and effortless.

1. What is SqlParameterSource?

In Spring JDBC, SqlParameterSource is an interface designed to provide named parameter values for SQL operations. Instead of manually putting entries into a standard Java Map, it provides structured mechanisms to supply parameter values:

  • MapSqlParameterSource: A flexible implementation that allows chaining parameter name-value pairs fluently via .addValue().
  • BeanPropertySqlParameterSource: Directly binds properties from a Java Bean or POJO to database column names using reflection.
  • Type Safety: Provides better support for explicit SQL type mapping when inserting custom or nullable types.

2. Using MapSqlParameterSource with SimpleJdbcInsert

MapSqlParameterSource is ideal when inserting dynamic data or when your data fields do not directly map to a single entity object:

  • Fluently Add Values: Use new MapSqlParameterSource().addValue("columnName", value) to map database fields.
  • Direct Execution: Pass the parameter source instance directly into simpleJdbcInsert.execute(parameters).
  • Cleaner Syntax: Avoids manual hash map instantiations and repetitive put() calls.

3. Simplifying POJO Inserts with BeanPropertySqlParameterSource

If you already have a domain object (such as an Employee or User bean):

  • Wrap the bean with new BeanPropertySqlParameterSource(myBean).
  • Spring automatically extracts getter properties and aligns them with matching table column names.
  • Minimizes boilerplate code and makes domain-driven persistence seamless.

4. Key Advantages

Combining SimpleJdbcInsert with SqlParameterSource gives you:

  • Zero Boilerplate SQL: No need to craft explicit INSERT INTO statements.
  • Less Human Error: Reduces typo risks associated with positional parameter placeholders (?).
  • Enhanced Maintainability: Code is cleaner, concise, and easier to test across enterprise data layers.

📺 Explore More Spring JDBC Tutorials

Continue expanding your Java and Spring knowledge with these related tutorials from our channel:

Wednesday, 6 March 2019

Spring - Specifying columns for SimpleJdbcInsert | Spring JDBC tutorial | Spring JDBC

🚀 Want to Master Spring & Java Development?

Subscribe to Ram N Java for beginner-friendly coding tutorials and practical guides!

🔔 Subscribe to YouTube Channel

Specifying Columns with SimpleJdbcInsert in Spring JDBC

While Spring JDBC’s SimpleJdbcInsert can automatically read all table columns through database metadata, real-world database design often requires inserting data only into selected columns. By explicitly configuring target columns with usingColumns(...), you gain precise control over your SQL insert statements while skipping default or auto-managed columns.

1. Why Restrict Columns with usingColumns()?

Explicitly declaring the columns for an insert operation provides key technical advantages:

  • Database Defaults: Allows the database to assign predefined default values (such as timestamps or UUIDs) to columns you choose to omit.
  • Improved Performance: Restricts metadata retrieval and query preparation strictly to the specified fields.
  • Prevent Unwanted Overwrites: Guarantees that unassigned entity properties do not accidentally push NULL into columns meant to retain system defaults.

2. Configuring usingColumns in SimpleJdbcInsert

Setting up usingColumns is straightforward and chains fluently with other configuration methods during initialization:

  • Define the Table Name: Use withTableName("table_name") to specify the target database table.
  • Chain usingColumns: Call usingColumns("col1", "col2", "col3") with the specific column names to be included in the generated INSERT query.
  • Thread Safety: Configure the SimpleJdbcInsert instance once during DAO initialization or bean creation so it remains thread-safe for all incoming requests.

3. Passing Parameters to the Operation

Once configured, you can execute the insert using Spring’s standard parameter mapping utilities:

  • MapSqlParameterSource: Provide named parameters via key-value chaining matching the specified column names.
  • BeanPropertySqlParameterSource: Pass a domain POJO; Spring matches getter method names directly to your declared columns.
  • Map<String, Object>: Use a standard Java map to dynamically supply values at runtime.

4. Practical Summary & Best Practices

Whenever a database table contains auto-generated IDs, audit timestamps, or default trigger columns, explicitly specifying columns with usingColumns(...) ensures clean, error-free inserts without generating manual SQL statements.

📺 Explore More Spring JDBC Tutorials

Continue expanding your Java and Spring knowledge with these related tutorials from our channel:

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

🚀 Want to Master Spring & Java Development?

Subscribe to Ram N Java for beginner-friendly coding tutorials and practical guides!

🔔 Subscribe to YouTube Channel

Inserting Data Using SimpleJdbcInsert in Spring JDBC

In standard JDBC and basic JdbcTemplate setups, executing insert statements often requires writing boilerplate SQL strings and mapping parameters manually. SimpleJdbcInsert is a powerful multi-threaded class provided by Spring JDBC that dramatically simplifies insert operations by utilizing database metadata to configure the insert statement automatically.

1. What is SimpleJdbcInsert?

SimpleJdbcInsert is part of the org.springframework.jdbc.core.simple package. It inspects table metadata directly through the JDBC driver, allowing you to execute inserts without manually writing the standard INSERT INTO table_name (...) VALUES (...) SQL statement:

  • Metadata Discovery: Reads column definitions and primary key configurations automatically.
  • Reduced Boilerplate: Eliminates tedious SQL query strings and placeholder parameter matching.
  • Clean Mapping: Accepts key-value pairs using Java Map implementations or bean property holders.

2. How to Configure SimpleJdbcInsert

To set up SimpleJdbcInsert in your Spring DAO or repository layer:

  • Initialize with DataSource: Instantiate SimpleJdbcInsert by passing the configured DataSource bean.
  • Define Table Name: Use the withTableName("table_name") method to specify your target table.
  • Specify Columns (Optional): You can optionally restrict operations to specific columns using usingColumns(...).
  • Auto-Generated Keys: Use usingGeneratedKeyColumns("column_name") if your table features auto-increment primary keys.

3. Executing the Insert Operation

Spring provides flexible ways to supply the data being inserted into the database:

  • Map-Based Execution: Pass a Map<String, Object> containing column names as keys and field values as map values directly to execute(parameters).
  • MapSqlParameterSource: A Spring utility class that simplifies building parameter maps with fluent chaining methods.
  • BeanPropertySqlParameterSource: Automatically maps getter methods on a POJO/domain model directly to matching database table columns.

4. Key Advantages of Using SimpleJdbcInsert

Leveraging SimpleJdbcInsert provides several practical benefits:

  • Cleaner DAO Classes: Your data access layer remains readable and free of repetitive SQL strings.
  • Fewer Syntax Mistakes: By avoiding manual SQL statement construction, column mismatch and type conversion bugs are minimized.
  • Effortless Key Retrieval: Retrieving generated database primary key IDs is handled seamlessly in a single step using executeAndReturnKey(...).

📺 Explore More Spring JDBC Tutorials

Continue expanding your Java and Spring knowledge with these related tutorials from our 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
  • Tutorials