Spirng框架对JDBC进行封装,使用JdbcTemplate方便实现对数据库的操作。
引入jdbc模块需要添加以下jar包:
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.21version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.3.9version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-ormartifactId>
<version>5.3.9version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>5.3.9version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.2.6version>
dependency>
然后写一个数据库的配置文件:
jdbc.properties:
注意:
1、下面的user_db是数据库的名称
2、prop.driverClass属性值,如果用mysql8.0就是 com.mysql.cj.jdbc.Driver,如果用mysql5.0就是com.mysql.jdbc.Driver
3、prop.url属性值,如果用mysql8.0需要加?&useSSL=false&serverTimezone=UTC,如果用的是mysql5.0,那么就直接写jdbc:mysql://localhost:3306/user_db即可。
4、prop.username和prop.password对应的是你自己的mysql的用户名和密码。
prop.driverClass=com.mysql.cj.jdbc.Driver
prop.url=jdbc:mysql://localhost:3306/user_db?&useSSL=false&serverTimezone=UTC
prop.username=root
prop.password=root
然后再在配置文件中开启注解扫描、引入外部属性文件、配置数据库连接池并创建JdbcTemplate对象,注入dataSource。
<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
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.example">context:component-scan>
<context:property-placeholder location="jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<property name="url" value="${prop.url}"/>
<property name="username" value="${prop.username}"/>
<property name="password" value="${prop.password}"/>
<property name="driverClassName" value="${prop.driverClass}"/>
bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource">property>
bean>
beans>
package com.example.po;
public class Book {
private Integer id;
private String name;
private Double price;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
}
要想使用jdbcTemplate对象实现添加操作,我们需要用到jdbcTemplate的update方法。
该方法的第一个参数是sql语句,第二个参数是可变参数,用来设置sql语句的值
然后我们编写其所对应的service和dao如下:
BookDao.java
package com.example.dao;
import com.example.po.Book;
public interface BookDao {
public void addBook(Book book);
}
BookDaoImpl.java
package com.example.dao;
import com.example.po.Book;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
@Repository
public class BookDaoImpl implements BookDao {
//注入jdbcTemplate
@Resource
private JdbcTemplate jdbcTemplate;
@Override
public void addBook(Book book) {
//创建sql语句
String sql = "insert into book values(?,?,?)";
//调用方法实现,返回成功修改的记录数
Object[] args = {book.getId(),book.getName(),book.getPrice()};
int num = jdbcTemplate.update(sql,args);
System.out.println("成功添加了 "+num+" 条记录");
}
}
BookService.java
package com.example.service;
import com.example.dao.BookDao;
import com.example.po.Book;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class BookService {
//注入bookDao
@Resource
private BookDao bookDao;
public void addBook(Book book){
bookDao.addBook(book);
}
}
然后我们编写一个测试类:
package com.example.dao;
import com.example.po.Book;
import com.example.service.BookService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class JdbcTest {
@Test
public void testJdbcTemplate(){
ApplicationContext context = new ClassPathXmlApplicationContext("jdbcContext.xml");
BookService bookService = context.getBean("bookService",BookService.class);
Book book = new Book();
book.setId(1);
book.setName("西游记");
book.setPrice(99.9);
bookService.addBook(book);
}
}
先修改BookDao.java,添加对应的接口
package com.example.dao;
import com.example.po.Book;
public interface BookDao {
public void addBook(Book book);
public void updateBook(Book book);
public void deleteBookById(Integer id);
}
然后修改BookDaoImpl.java,实现接口。
package com.example.dao;
import com.example.po.Book;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
@Repository
public class BookDaoImpl implements BookDao {
//注入jdbcTemplate
@Resource
private JdbcTemplate jdbcTemplate;
@Override
public void addBook(Book book) {
//创建sql语句
String sql = "insert into book values(?,?,?)";
//调用方法实现,返回成功修改的记录数
Object[] args = {book.getId(),book.getName(),book.getPrice()};
int num = jdbcTemplate.update(sql,args);
System.out.println("成功添加了 "+num+" 条记录");
}
/*修改记录*/
@Override
public void updateBook(Book book) {
String sql = "update book set name = ?, price = ? where id = ?";
Object[] args = {book.getName(),book.getPrice(),book.getId()};
int num = jdbcTemplate.update(sql,args);
System.out.println("成功修改了 "+num+" 条记录");
}
/*删除记录*/
@Override
public void deleteBookById(Integer id) {
String sql = "delete from book where id = ?";
int num = jdbcTemplate.update(sql,id);
System.out.println("成功删除了 "+num+" 条记录");
}
}
修改BookService.java,实现接口调用:
package com.example.service;
import com.example.dao.BookDao;
import com.example.po.Book;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class BookService {
//注入bookDao
@Resource
private BookDao bookDao;
public void addBook(Book book){
bookDao.addBook(book);
}
public void updateBook(Book book){
bookDao.updateBook(book);
}
public void deleteBook(Integer id){
bookDao.deleteBookById(id);
}
}
最后编写测试类:
@Test
public void testJdbcTemplateUpdate(){
ApplicationContext context = new ClassPathXmlApplicationContext("jdbcContext.xml");
BookService bookService = context.getBean("bookService",BookService.class);
Book book = new Book();
book.setId(1);
book.setName("水浒传");
book.setPrice(99.9);
bookService.updateBook(book);
}
@Test
public void testJdbcTemplateDelete(){
ApplicationContext context = new ClassPathXmlApplicationContext("jdbcContext.xml");
BookService bookService = context.getBean("bookService",BookService.class);
bookService.deleteBook(1);
}
运行testJdbcTemplateUpdate方法后,数据库信息如下:
再运行testJdbcTemplateDelete方法,数据库信息如下:
注意:现实中运用的话,不建议直接删除数据,毕竟现在是信息时代,每一条数据都异常宝贵,因此,更建议给每条记录 多写一个变量来表示这条数据要不要显示。比如,bool值,true就显示,删除就把值置false。
我们先给表格添加几条数据如下:
insert into book values(1,"西游记",100),(2,"水浒传",100),(3,"三国演义",100),(4,"红楼梦",100);
案例:查询表中有多少条记录,返回记录数
老规矩,先在BookDao中加:
public int findCount();
然后在BookDaoImpl中实现:
/*查询表中记录数*/
@Override
public int findCount() {
String sql = "select count(*) from book";
/*第一个参数是sql语句,第二个参数是返回的类,如果是字符串,那么就是String.class*/
Integer count = jdbcTemplate.queryForObject(sql,Integer.class);
return count;
}
然后在BookService中调用接口:
public int findCount(){
return bookDao.findCount();
}
最后写个测试类:
@Test
public void testJdbcTemplateFindCount(){
ApplicationContext context = new ClassPathXmlApplicationContext("jdbcContext.xml");
BookService bookService = context.getBean("bookService",BookService.class);
int count = bookService.findCount();
System.out.println("book表中共有"+count+"条记录");
}
案例:查询书名为西游记的详细信息
在UserDao中添加:
public Book findBookByName(String name);
在BookDaoImpl中实现:
/*通过书名查书*/
@Override
public Book findBookByName(String name) {
String sql = "select * from book where name = ?";
/*
* 第一个参数是sql语句
* 第二个参数是BeanPropertyRowMapper对象,<>中是返回的对象类型,()中是该对象的类
* 第三个对象是传入的参数
* */
Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Book>(Book.class), name);
return book;
}
知识点:jdbcTemplate.queryForObject中的第二个参数RowMapperhi接口,针对返回不同类型的数据,使用这个接口的实现类可以自动完成数据封装。
在BookService中调用接口:
public Book findBookByName(String name) {
return bookDao.findBookByName(name);
}
编写测试类:
@Test
public void testJdbcTemplateFindBookByName(){
ApplicationContext context = new ClassPathXmlApplicationContext("jdbcContext.xml");
BookService bookService = context.getBean("bookService",BookService.class);
Book book = bookService.findBookByName("西游记");
System.out.println(book);
}
为了方便查看数据,我们在Book.java中写一个toString方法:
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
'}';
}
BookDao:
public List<Book> findAll();
BookDaoImpl:(使用query方法,返回的是List集合,其他的跟上面查询对象基本一样)
@Override
public List<Book> findAll() {
String sql = "select * from book";
List<Book> books = jdbcTemplate.query(sql,new BeanPropertyRowMapper<Book>(Book.class));
return books;
}
BookService:
public List<Book> findAll(){
return bookDao.findAll();
}
测试方法:
@Test
public void testJdbcTemplateFindAll(){
ApplicationContext context = new ClassPathXmlApplicationContext("jdbcContext.xml");
BookService bookService = context.getBean("bookService",BookService.class);
List<Book> books = bookService.findAll();
for (Book book : books){
System.out.println(book);
}
}
使用jdbc的方法barchUpdate(String sql, List
他的底层实现逻辑是:将传进入的每个Object[]作为一个组合,然后放到List中。再将每个组合抽离出来,用我们的sql语句逐一进行实现。
简而言之,其实底层就是帮我们封装完后实现多次update(sql, Object[]);
老规矩,先在BookDao中添加代码:
public void addBooks(List<Object[]> books);
在BookDaoImpl中实现:
@Override
public void addBooks(List<Object[]> books) {
String sql = "insert into book values(?,?,?)";
int[] num = jdbcTemplate.batchUpdate(sql, books);
System.out.println(Arrays.toString(num));
}
在BookService中调用接口:
public void addBooks(List<Object[]> books){
bookDao.addBooks(books);
}
编写测试方法实现:
@Test
public void testJdbcTemplateAddBooks(){
ApplicationContext context = new ClassPathXmlApplicationContext("jdbcContext.xml");
BookService bookService = context.getBean("bookService",BookService.class);
Object[] book1 = {5,"C语言从入门到放弃",50.0};
Object[] book2 = {6,"C++从入门到入土",50.0};
Object[] book3 = {7,"Java是全世界最好的语言",50.0};
List<Object[]> books = new ArrayList<>();
books.add(book1);
books.add(book2);
books.add(book3);
bookService.addBooks(books);
}
BookDao:
public void updateBooks(List<Object[]> books);
public void deleteBooks(List<Object[]> ids);
BookDaoImpl:
//批量修改
@Override
public void updateBooks(List<Object[]> books) {
String sql = "update book set name = ?,price = ? where id = ?";
int[] num = jdbcTemplate.batchUpdate(sql, books);
System.out.println(Arrays.toString(num));
}
//批量删除
@Override
public void deleteBooks(List<Object[]> ids) {
String sql = "delete from book where id = ?";
int[] num = jdbcTemplate.batchUpdate(sql, ids);
System.out.println(Arrays.toString(num));
}
BookService:
public void updateBooks(List<Object[]> books){
bookDao.updateBooks(books);
}
public void deleteBooks(List<Object[]> ids){
bookDao.deleteBooks(ids);
}
测试类:
//测试批量修改
@Test
public void testJdbcTemplateUpdateBooks(){
ApplicationContext context = new ClassPathXmlApplicationContext("jdbcContext.xml");
BookService bookService = context.getBean("bookService",BookService.class);
/*注意顺序*/
Object[] book1 = {"Spring",60.0,1};
Object[] book2 = {"Spring MVC",60.0,2};
Object[] book3 = {"MyBatis",60.0,3};
List<Object[]> books = new ArrayList<>();
books.add(book1);
books.add(book2);
books.add(book3);
bookService.updateBooks(books);
}
//测试批量删除
@Test
public void testJdbcTemplateDeleteBooks(){
ApplicationContext context = new ClassPathXmlApplicationContext("jdbcContext.xml");
BookService bookService = context.getBean("bookService",BookService.class);
Object[] id_1 = {4};
Object[] id_2 = {5};
Object[] id_3 = {6};
List<Object[]> ids = new ArrayList<>();
ids.add(id_1);
ids.add(id_2);
ids.add(id_3);
bookService.deleteBooks(ids);
}