Spring JDBC是Spring框架提供的用于简化JDBC编程的模块,它封装了JDBC的繁琐的操作,提供了一套简单易用的API,可以帮助开发者更加轻松的访问和操作数据库。
Spring JDBC的主要特征:
使用 Spring JDBC 可以大大简化数据库访问的流程,减少了开发者的工作量,提高了开发效率,并且使代码更加清晰和易于维护。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.13</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<?xml version="1.0" encoding="UTF-8"?><!-- XML声明,xml版本和编码格式 -->
<!-- spring配置文件起点 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--
配置数据源
DriverManagerDataSource: spring框架提供的一个数据源实现类,用于管理和配置基于JDBC的数据源,
它实现了Java.sql.DataSource接口,可以被用于其他Spring JDBC API的数据源
-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 数据库连接驱动 -->
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<!-- 数据库连接URL -->
<property name="url" value="jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8"/>
<!-- 数据库连接用户名 -->
<property name="username" value="root"/>
<!-- 数据库连接密码 -->
<property name="password" value="123456"/>
</bean>
</beans>
create table user(
id int primary key auto_increment comment '主键id',
name varchar(20) character set utf8mb4 not null comment '姓名',
email varchar(20) character set utf8mb4 not null comment '邮箱'
)charset =utf8mb4;
insert into user(name, email) values('张三','123@qq.com');
package com.sin.pojo;
public class User {
private long id;
private String name;
private String email;
public User(){
}
public User(String name, String email) {
this.name = name;
this.email = email;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
'}';
}
}
package com.sin.dao;
import com.sin.pojo.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
/**
* @createTime 2024/1/4 11:52
* @createAuthor SIN
* @use
*/
public class UserDao {
private JdbcTemplate jdbcTemplate;
public void setDatabase(DataSource database){
this.jdbcTemplate = new JdbcTemplate(database);
}
public User getUserById(int id){
String sql = "SELECT * FROM user WHERE id = ? ";
return jdbcTemplate.queryForObject(sql,new Object[]{id},new BeanPropertyRowMapper<>(User.class));
}
public void addUser(User user){
String sql = "INSERT INTO user (id,name,email) VALUES (?,?,?)";
jdbcTemplate.update(sql,user.getId(),user.getName(),user.getEmail());
}
}
<!-- 配置bean -->
<bean id="userDao" class="com.sin.dao.UserDao">
<!--
name : 属性名,映射到UserDao类中的setDatabase()方法中
ref : 属性值,引用数据源中的Bean
-->
<property name="database" ref="dataSource"/>
</bean>
为什么database映射的是setDatabase方法呢???
在 Spring 中,属性名和对应的 setter 方法名遵循一定的命名规则即为驼峰命名法。具体来说,如果一个属性的名称是 database,则对应的 setter 方法应该命名为 setDatabase。? 因为,在 Spring 中,通过反射机制来调用 setter 方法时,会根据属性名称自动生成方法名,并自动调用该方法进行属性的注入。因此,我们需要严格遵循属性和方法的命名规则,以确保属性能够正确地被注入到对象中。
如果属性名为database1,那么需要映射的方法名为setDatabase1
package com.sin.service;
import com.sin.dao.UserDao;
import com.sin.pojo.User;
import org.springframework.stereotype.Service;
/**
* @createTime 2024/1/3 14:37
* @createAuthor SIN
* @use
*/
public interface UserService {
public void setUserDao(UserDao userDao);
public User getUserById(int userId);
public void addUser(User user);
}
package com.sin.service.impl;
import com.sin.dao.UserDao;
import com.sin.pojo.User;
import com.sin.service.UserService;
import org.springframework.stereotype.Service;
/**
* @createTime 2024/1/3 15:14
* @createAuthor SIN
* @use
*/
@Service
public class UserServiceImpl implements UserService {
private UserDao userDao;
@Override
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public User getUserById(int userId) {
return userDao.getUserById(userId);
}
@Override
public void addUser(User user) {
userDao.addUser(user);
}
}
<bean id="userService" class="com.sin.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean>
package com.sin.test;
import com.sin.pojo.User;
import com.sin.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @createTime 2024/1/4 9:17
* @createAuthor SIN
* @use
*/
public class AppTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService",UserService.class);
User user = new User("李四","123456@11.com");
userService.addUser(user);
System.out.println(userService.getUserById(1));
System.out.println(userService.getUserById(2));
}
}
JdbcTemplate是Spring框架提供的一个用于简化JDBC操作的工具类,它封装了一系列常用的数据库操作方法,能够更好的帮助我们进行数据库的增删改查的操作。
方法 | 说明 |
---|---|
query(String sql, RowMapper rowMapper) | 执行查询操作,并将结果映射为一个对象列表。sql 参数为查询语句,rowMapper 参数为结果集的映射器 |
queryForObject(String sql, RowMapper rowMapper) | 执行查询操作,并返回单个对象。如果查询结果为空或多于一个对象,则会抛出异常 |
queryForList(String sql) | 执行查询操作,并将结果映射为一个列表。适用于返回一列或多列的结果 |
update(String sql) | 执行更新操作,如插入、更新和删除等。sql 参数为要执行的更新语句 |
update(String sql, Object… args) | 执行带参数的更新操作。sql 参数为带有占位符的更新语句,args 参数为占位符的值 |
batchUpdate(String sql, List<Object[]> batchArgs) | 批量执行更新操作。sql 参数为要执行的更新语句,batchArgs 参数为批量更新的参数列表 |
execute(String sql) | 执行任意的 SQL 语句,如创建表、删除表等 |
call(CallableStatementCreator csc, List declaredParameters) | 调用存储过程或函数 |
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.13</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<?xml version="1.0" encoding="UTF-8"?><!-- XML声明,xml版本和编码格式 -->
<!-- spring配置文件起点 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.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/demo?useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
</beans>
package com.sin.dao;
import com.sin.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import javax.sql.DataSource;
import java.util.List;
/**
* @createTime 2024/1/4 11:52
* @createAuthor SIN
* @use
*/
@Repository // 表示该类为dao层
public class UserDao {
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource){
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public List<User> findAll() {
String sql = "SELECT * FROM user";
List<User> users = jdbcTemplate.query(sql, BeanPropertyRowMapper.newInstance(User.class));
return users;
}
public User findById(Long id) {
String sql = "SELECT * FROM user WHERE id = ? ";
return jdbcTemplate.queryForObject(sql,new Object[]{id},new BeanPropertyRowMapper<>(User.class));
}
public void save(User user) {
String sql = "INSERT INTO user(name, email) VALUES(?,?)";
Object[] args = {user.getName(), user.getEmail()};
jdbcTemplate.update(sql, args);
}
public void update(User user) {
String sql = "UPDATE user SET name=?, email=? WHERE id=?";
Object[] args = {user.getName(), user.getEmail(), user.getId()};
jdbcTemplate.update(sql, args);
}
public void delete(Long id) {
String sql = "DELETE FROM user WHERE id=?";
Object[] args = {id};
jdbcTemplate.update(sql, args);
}
}
<bean id="userDao" class="com.sin.dao.UserDao">
<property name="dataSource" ref="dataSource"/>
</bean>
package com.sin.service;
import com.sin.pojo.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import java.util.List;
/**
* @createTime 2024/1/5 9:08
* @createAuthor SIN
* @use
*/
public interface UserService {
public List<User> findAll();
public User findById(Long id);
public void save(User user);
public void update(User user);
public void delete(Long id);
}
package com.sin.service.impl;
import com.sin.dao.UserDao;
import com.sin.pojo.User;
import com.sin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.test.context.ContextConfiguration;
import java.util.List;
/**
* @createTime 2024/1/5 9:09
* @createAuthor SIN
* @use
*/
@Service
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public List<User> findAll() {
return userDao.findAll();
}
@Override
public User findById(Long id) {
return userDao.findById(id);
}
@Override
public void save(User user) {
if (user != null) {
userDao.save(user);
}
}
@Override
public void update(User user) {
userDao.update(user);
}
@Override
public void delete(Long id) {
if (id != null) {
userDao.delete(id);
}
}
}
<bean id="userService" class="com.sin.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean>
package com.sin.test;
import com.sin.pojo.User;
import com.sin.service.UserService;
import com.sin.service.impl.UserServiceImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
/**
* @createTime 2024/1/5 9:21
* @createAuthor SIN
* @use
*/
public class UserServiceTest {
public static UserService getUserService() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
return applicationContext.getBean("userService", UserService.class);
}
@Test
public void testFindAll(){
List<User> users = getUserService().findAll();
for(User user : users){
System.out.println(user);
}
}
@Test
public void testFindById() {
User user = getUserService().findById(1L);
System.out.println(user);
}
@Test
public void testSave() {
User user = new User();
user.setName("张三");
user.setEmail("121212.@111");
getUserService().save(user);
}
@Test
public void testUpdate() {
User user = getUserService().findById(2L);
user.setName("李四");
user.setEmail("1212121212@11.com");
getUserService().update(user);
}
@Test
public void testDelete() {
getUserService().delete(1L);
}
}