Java开发中使用Spring JdbcTemplate连接MySQL数据库
介绍如何使用 Spring 的 JdbcTemplate 组件简化 Java 应用程序对 MySQL 数据库的 CRUD 操作,涵盖从 Bean 定义、接口实现到 XML 配置和测试用例的完整流程。
项目架构与核心类设计
在使用 Spring JDBC 进行开发时,通常遵循分层架构设计。我们需要先定义数据模型(Bean)、访问接口(Service Interface)以及具体实现类(ServiceImpl),最后通过配置文件注入依赖。
第1步:定义数据实体 PersonBean
目的:建立与数据库表结构对应的 Java 对象,用于数据的封装。
首先创建位于 cn.com.bean 包下的实体类。该类主要包含 id 和 name 两个字段,并提供相应的构造函数及 Getter/Setter 方法。
package cn.com.bean;
public class PersonBean {
private int id;
private String name;
public PersonBean(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
第2步:创建 Service 接口 PersonService
目的:定义业务层的数据操作规范,解耦实现细节。
在 cn.com.service 包中定义接口,声明保存、更新、查询单个对象、查询所有对象以及删除记录的方法签名。
package cn.com.service;
import java.util.List;
import cn.com.bean.PersonBean;
public interface PersonService {
// 保存记录
public void save(PersonBean person);
// 更新记录
public void update(PersonBean person);
// 根据ID获取person
public PersonBean getPerson(int id);
// 获取所有person列表
public List<PersonBean> getPersonBean();
// 删除记录
public void delete(int personid);
}
核心逻辑实现
第3步:实现 Service 接口并使用 JdbcTemplate
入口:cn.com.service.impl 包。
动作:实现 PersonService 接口,利用 Spring 提供的 JdbcTemplate 执行 SQL 语句。
关键参数:DataSource(数据源)、JdbcTemplate、类型标识常量。
实现类通过 setter 方法接收外部的 DataSource 实例,并在内部实例化 JdbcTemplate。在执行 SQL 时,使用占位符 ? 配合参数数组以提高安全性。
package cn.com.service.impl;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import cn.com.bean.PersonBean;
import cn.com.service.PersonService;
public class PersonServiceImpl implements PersonService {
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public void save(PersonBean person) {
jdbcTemplate.update(
"insert into person(name) values(?)",
new Object[]{person.getName()},
new int[]{java.sql.Types.VARCHAR}
);
}
@Override
public void update(PersonBean person) {
jdbcTemplate.update(
"update person set name=? where id=?",
new Object[]{person.getName(), person.getId()},
new int[]{java.sql.Types.VARCHAR, java.sql.Types.INTEGER}
);
}
@Override
public PersonBean getPerson(int id) {
return (PersonBean) jdbcTemplate.queryForObject(
"select * from person where id=?",
new Object[]{id},
new int[]{java.sql.Types.INTEGER},
new PersonRowMapper()
);
}
@SuppressWarnings("unchecked")
@Override
public List<PersonBean> getPersonBean() {
return (List<PersonBean>) jdbcTemplate.query(
"select * from person",
new PersonRowMapper()
);
}
@Override
public void delete(int personid) {
jdbcTemplate.update(
"delete from person where id=?",
new Object[]{personid},
new int[]{java.sql.Types.INTEGER}
);
}
}
第4步:配置 RowMapper 结果集映射
作用:将数据库返回的 ResultSet 每一行转换为 PersonBean 对象。
由于 JdbcTemplate 不会自动映射复杂的对象,需要自定义一个实现 RowMapper 接口的类 PersonRowMapper。
package cn.com.service.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import cn.com.bean.PersonBean;
public class PersonRowMapper implements RowMapper {
@Override
public Object mapRow(ResultSet rs, int index) throws SQLException {
PersonBean person = new PersonBean(rs.getString("name"));
person.setId(rs.getInt("id"));
return person;
}
}
配置文件与数据库环境
第5步:编写 beans.xml 配置数据源与服务
内容:声明数据源、事务管理器、以及 PersonService 的 Bean。
注意:以下配置基于较旧版本的 Spring (Schema 2.5) 与 Apache DBCP 连接池。若使用较新版本,建议使用 HikariCP 或 Spring Boot 自动配置方式。
- 数据源配置:使用
org.apache.commons.dbcp.BasicDataSource。 - 连接属性:包括驱动类名(
com.mysql.jdbc.Driver)、URL、用户名和密码。 - 池参数:配置了初始大小(
initialSize=1)、最大活跃数(maxActive=500)等参数以优化性能。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/wy"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
<property name="initialSize" value="1"/>
<property name="maxActive" value="500"/>
<property name="maxIdle" value="2"/>
<property name="minIdle" value="1"/>
</bean>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
<bean id="personService" class="cn.com.service.impl.PersonServiceImpl">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
第6步:准备数据库表结构
确保数据库中已存在对应的 person 表,引擎建议采用 InnoDB 以支持事务。
CREATE TABLE `person` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8
单元测试验证
编写基于 JUnit 4 的测试类来验证 Spring 容器能否正确加载配置并执行数据操作。
package Junit.test;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.com.bean.PersonBean;
import cn.com.service.PersonService;
public class PersonTest2 {
private static PersonService personService;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
// 加载Spring配置文件
ApplicationContext act = new ClassPathXmlApplicationContext("beans.xml");
personService = (PersonService) act.getBean("personService");
}
@Test
public void save() {
personService.save(new PersonBean("wyy"));
}
@Test
public void update() {
PersonBean person = personService.getPerson(1);
if(person != null) {
person.setName("wy");
personService.update(person);
}
}
@Test
public void getPerson() {
PersonBean person = personService.getPerson(1);
System.out.println(person.getName());
}
@Test
public void delete() {
personService.delete(1);
}
}
排错与注意事项
- 版本匹配:原文使用的 Schema 为 2.5,且使用了
commons-dbcp。现代 Spring Boot 应用通常不再手动配置此类 XML,而是使用HikariCP并通过application.yml配置数据源。如果在新项目中遇到,请检查是否引入了正确的 Commons-DBCP 依赖。 - 字符集问题:数据库 URL 中建议显式指定字符集,例如:
jdbc:mysql://localhost:3306/wy?useUnicode=true&characterEncoding=UTF-8,以防中文乱码。 - 安全提示:XML 配置中的密码
123仅为演示用途。在生产环境中,切勿硬编码密码,应使用外部化配置或环境变量。
以上就是基于 Spring JdbcTemplate 连接并操作 MySQL 数据库的详细内容,更多关于 Spring JDBC 开发优化的资料请关注本站其它相关文章!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













