1、场景:查询图书详情
2、JdbcTemplate 实现查询返回对象
第一个参数:sql 语句。
第二个参数:RowMapper 是接口,针对返回不同类型数据,使用这个接口里面实现类完成数据封装。
第三个参数:sql 语句值。
dao接口:
package com.wzy.jdbctemplate.dao;import com.wzy.jdbctemplate.pojo.Book;import java.util.List;public interface BookDao {List<Book> selectByList();}
dao接口实现类:
package com.wzy.jdbctemplate.dao.impl;import com.wzy.jdbctemplate.dao.BookDao;import com.wzy.jdbctemplate.pojo.Book;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.List;@Repository//创建对象public class BookDaoImpl implements BookDao {@Autowired//自动装配JdbcTemplate jdbcTemplate;@Overridepublic List<Book> selectByList() {String sql = "select * from book";List<Book> bookList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class));return bookList;}}
service层类:
package com.wzy.jdbctemplate.service;import com.wzy.jdbctemplate.dao.BookDao;import com.wzy.jdbctemplate.pojo.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;/** @Description: 查询返回集合* @Author: WangZiYao* @Date: 2021/8/15 16:30*/public List<Book> selectBookByList(){List<Book> books = bookDao.selectByList();return books;}}
测试类:
package com.wzy.jdbctemplate.test;import com.wzy.jdbctemplate.pojo.Book;import com.wzy.jdbctemplate.service.BookService;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import java.util.List;import static org.junit.Assert.*;public class BookServiceTest {ApplicationContext applicationContext =new ClassPathXmlApplicationContext("com/wzy/jdbctemplate/spring.xml");BookService bookService = applicationContext.getBean("bookService",BookService.class);@Testpublic void selectBookByList(){List<Book> books = bookService.selectBookByList();books.forEach(book -> System.out.println(book));}}
输出结果:
Book{id=1, username=’1086’, password=’123456’, email=’16515@163.com’} Book{id=2, username=’5565456fe’, password=’123456www’, email=’tom@atguigu.com’}
Book{id=3, username=’146846fef’, password=’789456wfff’, email=’jerry@atguigu.com’}
Book{id=4, username=’few1656564’, password=’4645646we’, email=’black@atguigu.com’}
Book{id=5, username=’fwefw1666’, password=’46445weww’, email=’white@atguigu.com’}
Process finished with exit code 0
