🐉目录
9 JdbcTemplate
9 JdbcTemplate
Spring 框架对 JDBC 进行了封装,使用 JdbcTemplate 方便实现对数据库操作
相关包:
百度网盘链接https://pan.baidu.com/s/1Gw1l6VKc-p4gdqDyD626cg?pwd=6666
创建properties配置文件
💥注意:高版本 MySQL 需要将 useSSL 设置为 false此外,还需将驱动器修改为适合 MySQL 的版本: mysql-connector-java各种版本下载链接https://mvnrepository.com/artifact/mysql/mysql-connector-java如果仍报错则将 com.mysql.jdbc.Driver 改为 com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/study?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
name=root
password=123456
driverClassName=com.mysql.cj.jdbc.Driver
study 数据库中的 book 表
导入语法:source sql 文件地址, 无法插入中文,请修改数据库编码为 utf-8
create table book(
bookid int(10) primary key auto_increment,
bookname varchar(50),
booksale double(7,2));
insert into book(bookname,booksale) values
('Spring揭秘',75.5),
('Spring实战',56),
('Spring源码深入解析',72);
创建 xml 文件
com.alibaba.druid.pool.DruidDataSource 用来配置连接池org.springframework.jdbc.core.JdbcTemplate 用来连接数据库
<?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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!--加载配置文件-->
<context:property-placeholder location="classpath:user.properties" file-encoding="UTF-8"/>
<!-- 数据库连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<property name="url" value="${url}" />
<property name="username" value="${name}" />
<property name="password" value="${password}" />
<property name="driverClassName" value="${driverClassName}" />
</bean>
<!-- JdbcTemplate 对象 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--注入 dataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 组件扫描 -->
<context:component-scan base-package="springstudy4"></context:component-scan>
</beans>
Book 类存储书籍信息 Dao 是数据库操作,其中 BookDao 为接口并且声明了对数据库操作的方法,BookDaoIml 类实现了 BookDao 接口 Service 是业务操作,可以调用 BookDao 接口中的方法 Test 类进行测试,通过 Service 类调用 BookDao 接口中的方法 |
创建 BookDao 接口
package springstudy4;
import java.util.List;
public interface BookDao {
//增
void add(Book book);
//批量添加
void batchAddBook(List<Object[]> batchArgs);
//删
void delete(int id);
//批量删除
void batchDeleteBook(List<Object[]> batchArgs);
//改
void update(Book book);
//批量修改
void batchUpdateBook(List<Object[]> batchArgs);
//查
int selectCount();
//查询返回对象
Book findBookInfo(int id);
//查询返回集合
List<Book> findAllBook();
}
创建 BookService 类
package springstudy4;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BookService {
//注入 dao
@Autowired
private BookDao bookDao;
//添加
public void addBook(Book book) {
bookDao.add(book);
}
//批量添加
public void batchAdd(List<Object[]> batchArgs) {
bookDao.batchAddBook(batchArgs);
}
//删除
public void deleteBook(int id) {
bookDao.delete(id);
}
//批量删除
public void batchDelete(List<Object[]> batchArgs) {
bookDao.batchDeleteBook(batchArgs);
}
//修改
public void updateBook(Book book) {
bookDao.update(book);
}
//批量添加
public void batchUpdate(List<Object[]> batchArgs) {
bookDao.batchUpdateBook(batchArgs);
}
//查找
public void findBook(int id) {
bookDao.findBookInfo(id);
}
//查找全部
public List<Book> findAll() {
return bookDao.findAllBook();
}
}
创建 Book 类
package springstudy4;
public class Book {
private int bookid;
private String bookname;
private double booksale;
public int getBookid() {
return bookid;
}
public void setBookid(int bookid) {
this.bookid = bookid;
}
public String getBookname() {
return bookname;
}
public void setBookname(String bookname) {
this.bookname = bookname;
}
public double getBooksale() {
return booksale;
}
public void setBooksale(double booksale) {
this.booksale = booksale;
}
@Override
public String toString() {
return "Book{" +
"bookid=" + bookid +
", bookname='" + bookname + '\'' +
", booksale=" + booksale +
'}';
}
}
👀创建 BookDaoIml 类(重点)👀
BookDaoIml 类定义了 CRUD 方法,通过 JdbcTemplate 模块可以对数据库中的一条或多条数据进行操作
package springstudy4;
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 java.util.Arrays;
import java.util.List;
@Repository
public class BookDaoImpl implements BookDao {
//注入 JdbcTemplate
@Autowired
private JdbcTemplate jdbcTemplate;
//增
@Override
public void add(Book book) {
String sql = "insert into book values(?,?,?)";
jdbcTemplate.update(sql, book.getBookid(), book.getBookname(), book.getBooksale());
}
//批量添加
@Override
public void batchAddBook(List<Object[]> batchArgs) {
String sql = "insert into book values(?,?,?)";
int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
System.out.println(Arrays.toString(ints));
}
//删
@Override
public void delete(int id) {
String sql = "delete from book where bookid=?";
int update = jdbcTemplate.update(sql, id);
System.out.println(update);
}
//批量删除
@Override
public void batchDeleteBook(List<Object[]> batchArgs) {
String sql = "delete from book where bookid=?";
int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
System.out.println(Arrays.toString(ints));
}
//改
@Override
public void update(Book book) {
String sql = "update book set bookname=?,booksale=? where bookid=?";
Object[] args = {book.getBookname(), book.getBooksale(),book.getBookid()};
int update = jdbcTemplate.update(sql, args);
System.out.println(update);
}
//批量修改
@Override
public void batchUpdateBook(List<Object[]> batchArgs) {
String sql = "update book set bookname=?,booksale=? where bookid=?";
int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
System.out.println(Arrays.toString(ints));
}
//查
@Override
public int selectCount() {
String sql = "select count(*) from book";
Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
return count;
}
//查询返回对象
@Override
public Book findBookInfo(int id) {
String sql = "select * from book where bookid=?";
//调用方法
Book book = jdbcTemplate.queryForObject(sql, new
BeanPropertyRowMapper<Book>(Book.class), id);
return book;
}
//查询返回集合
@Override
public List<Book> findAllBook() {
String sql = "select * from book";
//调用方法
List<Book> bookList = jdbcTemplate.query(sql, new
BeanPropertyRowMapper<Book>(Book.class));
return bookList;
}
}
创建 Test 类
package springstudy4;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("bean4.xml");
BookService bookService = context.getBean("bookService", BookService.class);
Book book = new Book();
List<Book> bookList;
List<Object[]> batchArgs = new ArrayList<>();
//查找所有
bookList = bookService.findAll();
for(Book i : bookList) {
System.out.println(i);
}
// //增加一条
// book.setBookid(5);
// book.setBookname("算法导论");
// book.setBooksale(65);
// bookService.addBook(book);
// //批量添加测试
// batchArgs.clear();
// Object[] a1 = {6,"java",26};
// Object[] a2 = {7,"c++", 66};
// Object[] a3 = {8,"MySQL",62};
// batchArgs.add(a1);
// batchArgs.add(a2);
// batchArgs.add(a3);
// //调用批量添加
// bookService.batchAdd(batchArgs);
//批量删除
batchArgs.clear();
Object[] b1 = {6};
Object[] b2 = {7};
batchArgs.add(b1);
batchArgs.add(b2);
//调用方法实现批量删除
bookService.batchDelete(batchArgs);
//批量修改
batchArgs.clear();
Object[] c1 = {"java", 66.5, 6};
Object[] c2 = {"c++", 77.0, 7};
Object[] c3 = {"MySQL",88.5, 8};
batchArgs.add(c1);
batchArgs.add(c2);
batchArgs.add(c3);
//调用方法实现批量修改
bookService.batchUpdate(batchArgs);
}
}