JDBC(Java DataBase Connectivity,Java 数据库连接), 一 种用于执行 SQL 语句的 Java API(Application Programming Interface , 应用程序设计接口 ),可以为多种关系数据库提供统一访问,由一组用 Java 语言编写的类和接口组成。
JDBCTemplate ,是一个 JDBC 的模板,Spring 封装了 JDBC 常用的操作,简化了 JDBC API 的使用和开发人员的工作,提供了便捷、安全和高效的访问数据库的方式。
简单示例:
首先在 pom.xml 文件中添加以下配置:
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.3.25version>
dependency>
然后创建一个带有 id 和 name 属性的 JDBC 表:
再根据 JDBC 表定义一个与之相映射的 JDBC 类:
package cn.edu.springdemo.jdbc;
public class JDBC {
public int id;
public String name;
public JDBC() {
super();
}
public JDBC(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "JDBC{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
接着,定义一个接口 JDBCDao ,声明一系列常用访问数据库的方法:
package cn.edu.springdemo.jdbc;
import java.util.List;
public interface JDBCDao {
public void add(JDBC jdbc);
public void delete(int id);
public void update(JDBC jdbc);
public JDBC select(int id);
public List<JDBC> selectAll();
}
再创建该接口的实现类 JDBCDaoImpl :
package cn.edu.springdemo.jdbc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository("JDBCDao")
public class JDBCDaoImpl implements JDBCDao {
@Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
@Autowired
private JdbcTemplate jdbcTemplate;
//增添
public void add(JDBC jdbc){
String sql = "INSERT INTO `jdbc` (`name`) VALUES (:name);";
SqlParameterSource sqlParameterSource = new BeanPropertySqlParameterSource(jdbc);
namedParameterJdbcTemplate.update(sql,sqlParameterSource);
}
/**
* 增添或者使用如下方法
* public void add(JDBC jdbc){
* String sql = "INSERT INTO `jdbc` (`name`) VALUES (?);";
* Object[] args = {jdbc.getName()};
* jdbcTemplate.update(sql,args);
* }
*/
//删除
public void delete(int id){
String sql = "DELETE FROM `jdbc` WHERE `id`=?;";
jdbcTemplate.update(sql,id);
}
//修改
public void update(JDBC jdbc){
String sql = "UPDATE `jdbc` SET `name`=? WHERE `id`=?;";
Object[] args = {jdbc.getName(),jdbc.getId()};
jdbcTemplate.update(sql,args);
}
//id查询
public JDBC select(int id){
String sql = "SELECT `id`,`name` FROM `jdbc` WHERE `id`=?;";
RowMapper<JDBC> list = new BeanPropertyRowMapper<>(JDBC.class);
return jdbcTemplate.queryForObject(sql,list,id);
}
//查询
public List<JDBC> selectAll(){
String sql = "SELECT `id`,`name` FROM `jdbc`;";
RowMapper<JDBC> rowMapper = new BeanPropertyRowMapper<>(JDBC.class);
List<JDBC> list = jdbcTemplate.query(sql,rowMapper);
return list;
}
}
另外在 resources 目录下创建 jdbc.properties ,添加以下内容:
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC
jdbc.user=root
jdbc.password=0123
acquireIncrement=5
initialPoolSize=10
minPoolSize=5
maxPoolSize=100
maxStatements=2
maxStatementsPerConnection=5
xml配置:
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="cn.edu.springdemo.jdbc" />
<context:property-placeholder location="classpath:jdbc.properties" />
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
<property name="acquireIncrement" value="${acquireIncrement}" />
<property name="initialPoolSize" value="${initialPoolSize}" />
<property name="minPoolSize" value="${minPoolSize}" />
<property name="maxPoolSize" value="${maxPoolSize}" />
<property name="maxStatements" value="${maxStatements}" />
<property name="maxStatementsPerConnection" value="${maxStatementsPerConnection}" />
bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
bean>
<bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg type="javax.sql.DataSource" ref="dataSource"/>
bean>
beans>
最后测试结果:
package cn.edu.springdemo.jdbc;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class JDBCTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("jdbc.xml");
JDBCDao jdbcDao = (JDBCDao) applicationContext.getBean("JDBCDao");
System.out.println("第一次查询:" + jdbcDao.selectAll());
JDBC jdbc = new JDBC();
jdbc.setName("赵子龙");
jdbcDao.add(jdbc); //新增
jdbc.setId(10106);
jdbc.setName("赵云");
jdbcDao.update(jdbc); //修改
System.out.println("第二次查询:" + jdbcDao.selectAll());
System.out.println("id查询:" + jdbcDao.select(10101));
jdbcDao.delete(10104); //删除
}
}