一、什么是JDBCTemplate
Spring对JDBC进行封装,方便对数据库进行操作
Java中DAO层、Service层和Controller层的意义
DAO(data access object),封装基本增删改查操作,与表格直接对应操作,一般是原子操作
Service:服务层,对多个DAO进行封装,构成服务
二、配置过程
1、导入jar包
2、在spring配置文件配置数据库连接池
<!-- 数据库连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<!--高版本jar包需要加入时区信息-->
<property name="url" value="jdbc:mysql:///user_db?serverTimezone=Asia/Shanghai"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
</bean>
3、配置JdbcTemplate对象,注入DataSource
<!--注入JdbcTemplate对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--注入dataSource-->
<property name="dataSource" ref="dataSource"> </property>
</bean>
4、创建Service类和dao类,在dao注入JdbcTemplate对象
开启组件扫描
<!--组件扫描-->
<context:component-scan base-package="com.uestc.spring5"></context:component-scan>
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service(value = "bookService")
public class BookService {
//注入DAO
@Autowired
private BookDao bookdao;
}
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class BookDaoImpl {
//注入JDBCTemplate
private JdbcTemplate jdbcTemplate;
}
三、增删改查
1、增删改
接口
import entity.Book;
public interface BookDao {
void add(Book book);
void update(Book book);
void delete(String id);
}
接口实现类
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class BookDaoImpl implements BookDao{
//注入JDBCTemplate
@Autowired
private JdbcTemplate jdbcTemplate;
//添加的方法
@Override
public void add(Book book) {
//创建sql语句
String sql = "insert into t_book values(?,?,?)";
Object[] args = {book.getUserId(), book.getUsername(), book.getUstatus()};
//调用方法实现
int update = jdbcTemplate.update(sql, args);
}
@Override
public void update(Book book) {
String sql = "update t_book set username=?, ustatus=? where user_id=?";
Object[] args = {book.getUsername(), book.getUstatus(), book.getUserId()};
int update = jdbcTemplate.update(sql, args);
System.out.println(update);
}
@Override
public void delete(String id) {
String sql = "delete from t_book where user_id=?";
int update = jdbcTemplate.update(sql, id);
System.out.println(update);
}
}
功能类
@Service(value = "bookService")
public class BookService {
//注入DAO
@Autowired
private BookDao bookDao;
public void addBook(Book book){ bookDao.add(book); }
public void updateBook(Book book){ bookDao.update(book); }
public void deleteBook(String id){ bookDao.delete(id); }
}
测试类
public class TestBook {
@Test
public void testJDBC(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
BookService bookService = context.getBean("bookService", BookService.class);
Book book = new Book();
book.setUserId("1");
book.setUsername("java");
book.setUstatus("a");
bookService.addBook(book);
}
.......
}
物体类
package entity;
public class Book {
private String userId;
private String username;
private String ustatus;
public String getUserId() { return userId; }
public String getUsername() { return username;}
public String getUstatus() { return ustatus; }
public void setUserId(String userId) { this.userId = userId; }
public void setUsername(String username) { this.username = username; }
public void setUstatus(String ustatus) { this.ustatus = ustatus; }
}
2、查
(1)查询返回某个值
@Override
public int selectCount() {
String sql = "select count(*) from t_book";
Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
return count;
}
(2)查询返回对象
三个参数分别是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;
}
重写string方法来打印查询到类的参数
(3)查询返回集合
参数与queryForObject()一样
@Override
public List<Book> findAll() {
String sql = "select * from t_book";
List<Book> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Book.class));
return list;
}
打印结果示例
[Book{userId='1', username='java', ustatus='a'}, Book{userId='2', username='golang', ustatus='a'}, Book{userId='3', username='python', ustatus='a'}]
3、批量操作
操作表里面多条记录
service层
public void addbatchAll(List<Object[]> batchArg){
bookDao.batchupdate(batchArg);
}
dao层
@Override
public void batchupdate(List<Object[]> batchArgs) {
String sql = "insert into t_book values(?,?,?)";
int[] batchUpdate = jdbcTemplate.batchUpdate(sql, batchArgs);
System.out.println(batchArgs);
}
测试代码
@Test
public void testJDBCbatchUpdate(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
BookService bookService = context.getBean("bookService", BookService.class);
List<Object[]> batchArg = new ArrayList<>();
batchArg.add(new String[]{"4", "c#", "a"});
batchArg.add(new String[]{"5", "yi language", "b"});
BookService bookService1 = bookService;
bookService1.addbatchAll(batchArg);
}
修改删除同理