Spring5框架04-JdbcTemplate
文章目录
一、概念和准备
1、什么是JdbcTemplate
(1)Spring框架对JDBC进行封装,使用JdbcTemplate方便实现对数据库操作
2、准备工作
(1)引入相关jar包
(2)在spring配置文件配置数据库连接池
<!-- 数据库连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<property name="url" value="jdbc:mysql:///user_db" />
<property name="username" value="root" />
<property name="password" value="jlq000321" />
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
</bean>
(3)配置JdbcTemplate对象,注入DataSource
<!--创建jdbcTemplate对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--注入-->
<property name="dataSource" ref="dataSource"/>
</bean>
(4)创建service类,创建dao类,在dao注入jdbcTemplate对象
<!--开启组件扫描-->
<context:component-scan base-package="com.micah"/>
package com.micah.spring.service;
import com.micah.spring.dao.BookDao;
import com.micah.spring.enity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BookService {
@Autowired
private BookDao bookDao;
}
package com.micah.spring.dao;
import com.micah.spring.enity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Repository
public class BookDaoImpl implements BookDao{
/**
* 注入JdbcTemplate
*/
@Autowired
private JdbcTemplate jdbcTemplate;
}
二、操作数据库(添加)
1、对应数据库创建实体类
package com.micah.spring.enity;
public class Book {
private int userId;
private String username;
private String userStatus;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserStatus() {
return userStatus;
}
public void setUserStatus(String userStatus) {
this.userStatus = userStatus;
}
}
2、编写service和dao
(1)在dao进行数据库添加操作
(2)调用JdbcTemplate对象里面update方法实现添加操作
有两个参数
第一个参数:sql语句
第二个参数:可变参数,设置sql语句值
package com.micah.spring.dao;
import com.micah.spring.enity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Repository
public class BookDaoImpl implements BookDao{
/**
* 注入JdbcTemplate
*/
@Autowired
private JdbcTemplate jdbcTemplate;
/**
* 添加方法
* @param book 书
*/
@Override
public void add(Book book) {
Object[] args = {book.getUserId(),book.getUsername(),book.getUserStatus()};
int update = jdbcTemplate.update("insert into t_user values (?,?,?)", args);
System.out.println("update successful!" + update);
}
}
3、测试类
package com.micah.spring.test;
import com.micah.spring.enity.Book;
import com.micah.spring.service.BookService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.ArrayList;
import java.util.List;
public class JdbcTemplateTest {
/**
* 单增
*/
@Test
public void testAdd(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
BookService bookService = context.getBean("bookService", BookService.class);
Book book = new Book();
book.setUserId(1);
book.setUsername("Micah");
book.setUserStatus("online");
bookService.addBook(book);
}
}
三、操作数据库(修改和删除)
1、修改
@Override
public void update(Book book) {
Object[] args = {book.getUsername(),book.getUserStatus(),book.getUserId()};
int update = jdbcTemplate.update("update t_user set username = ?,ustates = ? where user_id = ?", args);
System.out.println("update successful!" + update);
}
2、删除
@Override
public void deleteBook(String id) {
int update = jdbcTemplate.update("delete from t_user where user_id = ?", id);
System.out.println("delete successful!" + update);
}
四、操作数据库(查询返回某个值)
1、查询表里面有多少条记录,返回是某个值
2、使用JdbcTemplate实现查询返回某个值代码
有两个参数
第一个参数:sql语句
第二个参数:返回类型Class
@Override
public int selectCount() {
String sql = "select count(*) from t_user";
int count = jdbcTemplate.queryForObject(sql,Integer.class);
return count;
}
五、操作数据库(查询返回对象)
1、场景:查询图书详情
2、JdbcTemplate实现查询返回对象
有三个参数
第一个参数:sql语句
第二个参数:RowMapper是接口,针对返回不同类型数据,使用这个接口里面实现类完成数据封装
第三个参数:sql语句值
//查询返回对象
@Override
public Book findBookInfo(String id) {
String sql = "select * from t_book where user_id=?";
// 调用方法
Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Book>(Book.class), id);
return book;
}
六、操作数据库(查询返回集合)
1、场景:查询图书列表分页…
2、调用JdbcTemplate方法实现查询返回集合
有三个参数
第一个参数:sql语句
第二个参数:RowMapper是接口,针对返回不同类型数据,使用这个接口里面实现类完成数据封装
第三个参数:sql语句值
//查询返回集合
@Override
public List<Book> findAllBook() {
String sql = "select * from t_book";
// 调用方法
List<Book> bookList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class));
return bookList;
}
七、操作数据库 (批量操作)
1、批量操作:操作表里面多条记录
2、JdbcTemplate实现批量添加操作
有两个参数
第一个参数:sql语句
第二个参数:List集合,添加多条记录数据
//批量添加数据
@Override
public void batchAddBook(List<Object[]> books) {
String sql = "Insert into t_user values(?,?,?)";
int[] res = jdbcTemplate.batchUpdate(sql, books);
System.out.println(Arrays.toString(res));
}
@Test
public void testBatchAddBooks(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
BookService bookService = context.getBean("bookService", BookService.class);
List<Object[]> books = new ArrayList<>();
Object[] o1 = {"3", "java", "a"};
Object[] o2 = {"5", "C", "b"};
books.add(o1);
books.add(o2);
bookService.batchAddBook(books);
}
3、JdbcTemplate实现批量修改操作
@Override
public void batchUpdateBook(List<Object[]> books) {
String sql = "Update t_user set username = ?,ustates = ? where user_id = ?";
int[] res = jdbcTemplate.batchUpdate(sql, books);
System.out.println(Arrays.toString(res));
}
@Test
public void testBatchUpdate(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
BookService bookService = context.getBean("bookService", BookService.class);
List<Object[]> books = new ArrayList<>();
Object[] o1 = {"3", "Micah", "3"};
Object[] o2 = {"5", "Maruko", "5"};
books.add(o1);
books.add(o2);
bookService.batchUpdateBook(books);
}
4、JdbcTemplate实现批量删除操作
@Override
public void batchDelBook(List<Object[]> ids) {
String sql = "DELETE FROM t_user WHERE user_id = ?";
int[] res = jdbcTemplate.batchUpdate(sql, ids);
System.out.println(Arrays.toString(res));
}
@Test
public void testBatchDelete(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
BookService bookService = context.getBean("bookService", BookService.class);
List<Object[]> ids = new ArrayList<>();
Object[] o1 = {"3"};
Object[] o2 = {"5"};
ids.add(o1);
ids.add(o2);
bookService.batchDelBook(ids);
}
@Test
public void testBatchDelete(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
BookService bookService = context.getBean("bookService", BookService.class);
List<Object[]> ids = new ArrayList<>();
Object[] o1 = {"3"};
Object[] o2 = {"5"};
ids.add(o1);
ids.add(o2);
bookService.batchDelBook(ids);
}