1、maven依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.ly.spring</groupId>
<artifactId>spring04</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging> <dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.0.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

2、实体类

package com.ly.spring.domain;

import java.io.Serializable;

public class Account implements Serializable {
private Integer id;
private Integer uid;
private double money; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public Integer getUid() {
return uid;
} public void setUid(Integer uid) {
this.uid = uid;
} public double getMoney() {
return money;
} public void setMoney(double money) {
this.money = money;
} @Override
public String toString() {
return "Account{" +
"id=" + id +
", uid=" + uid +
", money=" + money +
'}';
}
}

3、Service接口

package com.ly.spring.service;

import com.ly.spring.domain.Account;

import java.sql.SQLException;
import java.util.List; public interface IAccountService {
public List<Account> findAll() throws SQLException;
public Account findOne(Integer id) throws SQLException;
public void save(Account account) throws SQLException;
public void update(Account account) throws SQLException;
public void delete(Integer id) throws SQLException;
}

4、Service实现类

package com.ly.spring.service.impl;

import com.ly.spring.dao.IAccountDao;
import com.ly.spring.domain.Account;
import com.ly.spring.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.sql.SQLException;
import java.util.List; @Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
public List<Account> findAll() throws SQLException {
return accountDao.findAll();
} @Override
public Account findOne(Integer id) throws SQLException {
return accountDao.findOne(id);
} @Override
public void save(Account account) throws SQLException {
accountDao.save(account);
} @Override
public void update(Account account) throws SQLException {
accountDao.update(account);
} @Override
public void delete(Integer id) throws SQLException {
accountDao.delete(id);
}
}

5、Dao接口

package com.ly.spring.dao;

import com.ly.spring.domain.Account;

import java.sql.SQLException;
import java.util.List; public interface IAccountDao {
public List<Account> findAll() throws SQLException;
public Account findOne(Integer id) throws SQLException;
public void save(Account account) throws SQLException;
public void update(Account account) throws SQLException;
public void delete(Integer id) throws SQLException;
}

6、Dao实现类

package com.ly.spring.dao.impl;

import com.ly.spring.dao.IAccountDao;
import com.ly.spring.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; import java.sql.SQLException;
import java.util.List; @Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private QueryRunner queryRunner;
public List<Account> findAll() throws SQLException {
return queryRunner.query("select * from account",new BeanListHandler<Account>(Account.class));
} @Override
public Account findOne(Integer id) throws SQLException {
return queryRunner.query("select * from account where id = ?",new BeanHandler<Account>(Account.class),id);
} @Override
public void save(Account account) throws SQLException {
queryRunner.update("insert into account(uid,money) values(?,?)",account.getUid(),account.getMoney());
} @Override
public void update(Account account) throws SQLException {
queryRunner.update("update account set money = ? where id = ?",account.getMoney(),account.getId());
} @Override
public void delete(Integer id) throws SQLException {
queryRunner.update("delete from account where id = ?",id);
}
}

7、jdbc资源文件

jdbc.url = jdbc:mysql://localhost:3306/db01
jdbc.driver = com.mysql.jdbc.Driver
jdbc.username = root
jdbc.password = root

8、spring主配置类

package com.ly.spring.config;
import org.springframework.context.annotation.*;
//@Configuration:用于标记此类为配置类
/**
* @Configuration说明:
* 1、若该类为new AnnotationConfigApplicationContext()的入参类型,则可以省略@Configuration注解
* 2、若该类是配置类但不是new AnnotationConfigApplicationContext()的入参类型(JdbcConfig.java),
* 且引入该配置类的方式是@ComponentScan而非@Import时,不可以省略@Configuration注解
* 3、若是通过@Import引入的该配置类(JdbcConfig.java),则被引入的配置类可省略@Configuration注解
* 4、@ComponentScan({"com.ly.spring","xx.xxx"})可以配置多个
*/
@Configuration
//@ComponentScan:用于指定spring注解扫描的包
@ComponentScan("com.ly.spring")
//@PropertySource:指定外部properties文件
@PropertySource("classpath:db.properties")
//@Import:引入另外一个配置类
/**
* @Import说明
* 1、若需要引入的类通过@ComponentScan可以被扫描到,且该类有@Configuration注解则不需要配置@Import注解引入该配置类
* 2、使用@Import引入配置类时,该配置类可以省略@Configuration注解
* 3、@Import({JdbcConfig.class,xxx.class}) 可以引入多个
*/
@Import(JdbcConfig.class)
public class SpringConfiguration { }

9、jdbc配置类

package com.ly.spring.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope; import javax.sql.DataSource; //@Configuration:用于标记此类为配置类
@Configuration
public class JdbcConfig {
//@Value:用于读取资源文件中指定key对用的值
@Value("${jdbc.url}")
private String jdbcUrl;
@Value("${jdbc.driver}")
private String jdbcDriver;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password; //@Bean用于在spring容器中创建方法返回值类型的bean,创建的bean默认id为方法名
//@Bean配置了name属性时即指定了创建的bean对应的id
@Bean
//@Scope:指定创建的bean的作用范围,默认是单例的
@Scope("singleton")
//当方法中有参数且没有@Qualifier注解指定bean的id时,会自动从spring容器中按照@Autowired注解的方式去注入bean
//当方法中有参数且有@Qualifier注解指定bean的id时,会根据指定的id去spring容器中寻找对应的bean
public QueryRunner getQueryRunner(@Qualifier("dataSource") DataSource dataSource) {
return new QueryRunner(dataSource);
} //name指定创建的bean在spring容器中的id
@Bean(name = "dataSource")
public DataSource getDataSource() {
try {
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
comboPooledDataSource.setDriverClass(jdbcDriver);
comboPooledDataSource.setJdbcUrl(jdbcUrl);
comboPooledDataSource.setUser(username);
comboPooledDataSource.setPassword(password);
return comboPooledDataSource;
}catch (Exception e) {
throw new RuntimeException(e);
}
}
}

10、测试类

package com.ly.spring.test;

import com.ly.spring.config.JdbcConfig;
import com.ly.spring.config.SpringConfiguration;
import com.ly.spring.domain.Account;
import com.ly.spring.service.IAccountService;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List; public class MainTest {
private AnnotationConfigApplicationContext context;
private IAccountService accountService;
@Before
public void init() {
//通过注解获取spring容器
//可以同时指定多个配置类
//context = new AnnotationConfigApplicationContext(SpringConfiguration.class, JdbcConfig.class);
context = new AnnotationConfigApplicationContext(SpringConfiguration.class);
accountService = context.getBean("accountService",IAccountService.class);
} @Test
public void testScope() {
DataSource dataSource1 = context.getBean("dataSource", DataSource.class);
DataSource dataSource2 = context.getBean("dataSource", DataSource.class);
System.out.println(dataSource1 == dataSource2); QueryRunner queryRunner1 = context.getBean("getQueryRunner", QueryRunner.class);
QueryRunner queryRunner2 = context.getBean("getQueryRunner", QueryRunner.class);
System.out.println(queryRunner1);
System.out.println(queryRunner1 == queryRunner2);
} @Test
public void findAll() throws SQLException {
List<Account> accounts = accountService.findAll();
System.out.println(accounts);
} @Test
public void findOne() throws SQLException {
Account account = accountService.findOne(3);
System.out.println(account);
} @Test
public void save() throws SQLException {
Account account = new Account();
account.setUid(52);
account.setMoney(6000);
accountService.save(account);
} @Test
public void update() throws SQLException {
Account account = new Account();
account.setId(5);
account.setMoney(100000);
accountService.update(account);
}
@Test
public void delete() throws SQLException {
accountService.delete(5);
}
}

11、补充spring整合junit,修改如下:

11.1、引入spring-test的jar包

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
<scope>test</scope>
</dependency>

11.2、在测试类中使用@RunWith注解替换junit的main方法

11.3、在测试类中使用@ContextConfiguration注解指定spring配置文件的位置或者spring配置类

package com.ly.spring.test;

import com.ly.spring.config.SpringConfiguration;
import com.ly.spring.domain.Account;
import com.ly.spring.service.IAccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.sql.SQLException;
import java.util.List;
//@RunWith:用于替换junit的main方法
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration:用于指定spring配置文件的位置或者spring配置类
/**
* @ContextConfiguration说明
* 1、locations用于指定spring配置文件的位置locations = "classpath:bean.xml"
* 2、classes用于指定spring配置类
*/
@ContextConfiguration(classes = SpringConfiguration.class)
public class MainTest {
@Autowired
private IAccountService accountService; @Test
public void findAll() throws SQLException {
List<Account> accounts = accountService.findAll();
System.out.println(accounts);
} @Test
public void findOne() throws SQLException {
Account account = accountService.findOne(3);
System.out.println(account);
} @Test
public void save() throws SQLException {
Account account = new Account();
account.setUid(52);
account.setMoney(6000);
accountService.save(account);
} @Test
public void update() throws SQLException {
Account account = new Account();
account.setId(5);
account.setMoney(100000);
accountService.update(account);
}
@Test
public void delete() throws SQLException {
accountService.delete(5);
}
}

11.4、SpringJUnit4ClassRunner requires JUnit 4.12 or higher报错解决

需升级junit版本4.12及以上

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>

commons-dbutils实现增删改查(spring新注解)的更多相关文章

  1. 使用DbUtils实现增删改查——ResultSetHandler 接口的实现类

    在上一篇文章中<使用DbUtils实现增删改查>,发现运行runner.query()这行代码时.须要自己去处理查询到的结果集,比較麻烦.这行代码的原型是: public Object q ...

  2. 增删改查Spring+MyBatis

    其实这次写这个增删改查,我的收获很大,在同学的帮助下和老师的推动下,我也是学会了很多的技能点. 1.显示数据 显示数据对我而言可以说很好做,因为我以前增删改查做了有N遍,但是我却每次都是无功而返,半途 ...

  3. DBUtils的增删改查

    数据准备: CREATE DATABASE mybase; USE mybase; CREATE TABLE users( uid INT PRIMARY KEY AUTO_INCREMENT, us ...

  4. Hibernate操作指南-实体与常用类型的映射以及基本的增删改查(基于注解)

  5. Spring JPA实现增删改查

    1. 创建一个Spring工程 2.配置application文件 spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver spri ...

  6. 增删改查——Statement接口

    1.增加数据表中的元组 package pers.datebase.zsgc; import java.sql.Connection; import java.sql.DriverManager; i ...

  7. SSM框架搭建(Spring+SpringMVC+MyBatis)与easyui集成并实现增删改查实现

    一.用myEclipse初始化Web项目 新建一个web project: 二.创建包 controller        //控制类 service //服务接口 service.impl //服务 ...

  8. Spring JdbcTemplate框架搭建及其增删改查使用指南

    Spring JdbcTemplate框架搭建及其增删改查使用指南 前言: 本文指在介绍spring框架中的JdbcTemplate类的使用方法,涉及基本的Spring反转控制的使用方法和JDBC的基 ...

  9. dbutils中实现数据的增删改查的方法,反射常用的方法,绝对路径的写法(杂记)

    jsp的三个指令为:page,include,taglib... 建立一个jsp文件,建立起绝对路径,使用时,其他jsp文件导入即可 导入方法:<%@ include file="/c ...

随机推荐

  1. Windows搭建IIS服务器使用NATAPP实现内网穿透

    目的:外网可以访问本地网页. 步骤: 一.实现内网访问 1.Win+Q搜索[控制面板],选择[程序],点击[启用或关闭Windows功能], 2.勾选[Internet Information Ser ...

  2. golang的timer一些坑

    本文代码部分基于dive-to-gosync-workshop的代码 Golang 的NewTimer方法调用后,生成的timer会放入最小堆,一个后台goroutine会扫描这个堆,将到时的time ...

  3. 《Head first设计模式》学习笔记

    1. 单例模式 2. 工厂模式 3. 抽象工厂 4. 策略模式 5. 观察者模式 6. 装饰者模式 7. 命令模式 8. 适配器模式 9. 外观模式 10. 模版方法模式 11. 迭代器模式 设计模式 ...

  4. ls-remote -h -t git://github.com/adobe-webplatform/eve.git

    npm WARN deprecated bfj-node4@5.3.1: Switch to the `bfj` package for fixes and new features! npm WAR ...

  5. 在Docker中运行SpringBoot程序

    1.将SpringBoot项目中pom.xml的build插件更换为: <build> <plugins> <plugin> <groupId>org. ...

  6. SAP VL10B 报错 - 4500000317 000010 交付 $ 1 的交付项目 000010 与 POD 无关-

    SAP VL10B 报错 - 4500000317 000010 交付 $ 1 的交付项目 000010 与 POD 无关- 如下公司间STO单据, 业务背景是货物从公司代码LYSP转入公司代码BTS ...

  7. Android布局管理器-使用LinearLayout实现简单的登录窗口布局

    场景 Android布局管理器-从实例入手学习相对布局管理器的使用: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/1038389 ...

  8. 高性能异步SRAM技术角度

    当前有两个不同系列的异步SRAM:快速SRAM(支持高速存取)和低功耗SRAM(低功耗).从技术角度看来,这种权衡是合理的.在低功耗SRAM中,通过采用特殊栅诱导漏极泄漏(GIDL)控制技术控制待机电 ...

  9. PMP--1.6 项目经理

    本节都是理论的东西,可以在管理没有思路的或者管理陷入困境的时候当做提升或解决问题的思路来看. 一.项目经理 1. 项目经理.职能经理与运营经理的区别 (1)职能经理专注于对某个职能领域或业务部门的管理 ...

  10. 并发编程之J.U.C的第二篇

    并发编程之J.U.C的第二篇 3.2 StampedLock 4. Semaphore Semaphore原理 5. CountdownLatch 6. CyclicBarrier 7.线程安全集合类 ...