经过前面的准备工作,我们已经创建了各种类,也做好了各种配置(见上篇博客),下面我们就要用JdbcTemplate操作数据库实现增加功能。
1、对应数据库创建实体类:
数据库创建:
创建对应的实体类Book:
package demo.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、在BookDaoImpl中实现增加方法
BookDao:
package demo.dao; import demo.entity.Book; public interface BookDao { //添加 public void addBook(Book book); }
BookDaoImpl:
package demo.dao; import demo.entity.Book; import org.springframework.beans.factory.annotation.Autowired; 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 addBook(Book book) { String sql = "insert into t_book values(?,?,?)"; Object[] args = {book.getUserId(), book.getUsername(), book.getUstatus()}; //使用update()方法实现增删改 int update = jdbcTemplate.update(sql, args); System.out.println(update); } }
JdbcTemplate中,使用update()方法实现数据库的增删改,其他代码是基础的jdbc知识
3、在BookService中调用增加方法:
package demo.service; import demo.dao.BookDao; import demo.entity.Book; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class BookService { //注入dao @Autowired private BookDao bookDao; //添加 public void addBook(Book book){ bookDao.addBook(book); } }
4、写个测试类测试一下
@Test public void test(){ ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml"); BookService bookService = context.getBean("bookService", BookService.class); Book book = new Book(); book.setUserId("1"); book.setUsername("java"); book.setUstatus("哈哈哈"); bookService.addBook(book); }
看一下运行结果:
控制台输出1,说明成功插入一条数据
再看看数据库:
可以看到成功插入数据
删除和修改操作也是同理,仅仅是sql语句的不同。