🚀 Ready to Master Spring JDBC?
Don't miss out on more easy-to-follow Java tutorials. Join Ram N Java today!
SUBSCRIBE TO CHANNELDeleting Records Using a Single Parameter
Deleting data safely and efficiently is a critical part of any database application. In this guide, we'll learn how to use Spring JdbcTemplate to execute a DELETE statement using a single dynamic parameter, such as an employee ID.
The SQL Delete Statement
When we want to delete a specific row, we use the WHERE clause with a placeholder (?). This is much safer than concatenating strings directly, as it protects against SQL injection.
Using JdbcTemplate's Update Method
In Spring JDBC, the update() method is versatile. It is used not only for updates and inserts but also for deletions. When dealing with a single parameter, the method signature is straightforward.
How it works:
- Query: Pass your SQL string with the
?placeholder. - Value: Pass the actual value (like the ID) that should replace the
?.
Beginner-Friendly Logic
- Identify the Target: Determine which column (e.g., ID or Name) you'll use to filter the deletion.
- Inject JdbcTemplate: Ensure your DAO or Service has access to the
JdbcTemplateobject. - Execute: Call
jdbcTemplate.update(sql, parameterValue). Spring handles the database connection and statement cleanup for you!
⭐ Important Note:
The update() method returns an int. This value represents the total number of rows deleted. If it returns 1, one record was successfully removed. If 0, no matching record was found.
Keep Learning with Ram N Java
Check out these related tutorials from our channel to expand your Spring JDBC skills:
Click here to watch on Youtube:
https://www.youtube.com/watch?v=OgR-AcRtN0Y&list=UUhwKlOVR041tngjerWxVccw
Click the below Image to Enlarge:
| Spring + JdbcTemplate + Execute delete statement with one parameter example | Spring JDBC tutorial |
Employee.sql
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
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
public interface EmployeeDAO
{
public void deleteByEmployeeId(int employeeId);
}
EmployeeDAOImpl.java
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import com.ram.employee.dao.EmployeeDAO;
public class EmployeeDAOImpl
extends JdbcDaoSupport implements EmployeeDAO
{
public void deleteByEmployeeId(int employeeId)
{
String sql = "DELETE FROM EMPLOYEE WHERE EMPLOYEE_ID=?";
getJdbcTemplate().update(sql, employeeId);
}
}
applicationContext.xml
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
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.deleteByEmployeeId(1);
System.out.println("employee row deleted successfully.");
}
}
Output:
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@35d176f7: startup date [Fri Feb 08 10:17:37 IST 2019]; root of context hierarchy
Feb 08, 2019 10:17:37 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 08, 2019 10:17:38 AM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
Fri Feb 08 10:17:51 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.
ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
JDWP exit error AGENT_ERROR_NO_JNI_ENV(183): [util.c:840]
employee row deleted successfully.
Click the below link to download the code:
https://sites.google.com/site/javaspringram2019/java_spring_2019/SpringDemo_delete_one_param.zip?attredirects=0&d=1
Github Link:
https://github.com/ramram43210/Java_Spring_2019/tree/master/Spring_2019/SpringDemo_delete_one_param
Bitbucket Link:
https://bitbucket.org/ramram43210/java_spring_2019/src/a3741618d82a4fb8b8d7a6751e0e628f0b8999ea/Spring_2019/SpringDemo_delete_one_param/?at=master
See also:
No comments:
Post a Comment