spring+c3p0连接池+dbutils+mysql+junit测试基于注解实现ioc编程

2021/7/16 19:06:17

本文主要是介绍spring+c3p0连接池+dbutils+mysql+junit测试基于注解实现ioc编程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

标题spring+c3p0连接池+dbutils+mysql+junit测试基于注解实现ioc编程

(1)导入spring,c3p0,dbutilsr,junit,dbutils的依赖坐标到pom.xml,导入后idea会自动从网上下载相关jar包。

<?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>xjit</groupId>
    <artifactId>cm</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.40</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
<!--        QueryRunner 中提供对sql语句操作的API.-->
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.4</version>
        </dependency>
<!--            普通的JDBC数据库连接使用 DriverManager 来获取,每次向数据库建立连接的时候都要将 Connection 加载到内存中,-->
<!--            再验证用户名和密码(得花费0.05s~1s的时间)。需要数据库连接的时候,就向数据库要求一个,执行完成后再断开连接。-->
<!--            这样的方式将会消耗大量的资源和时间。数据库的连接资源并没有得到很好的重复利用.若同时有几百人甚至几千人在线,-->
<!--            频繁的进行数据库连接操作将占用很多的系统资源,严重的甚至会造成服务器的崩溃。-->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
<!--        JUnit 促进了“先测试后编码”TDD的理念,强调建立测试数据的一段代码,可以先测试,然后再应用。-->
<!--        这个方法就好比“测试一点,编码一点,测试一点,编码一点……”,增加了程序员的产量和程序的稳定性,可以减少程序员的压力和花费在排错上的时间。-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>
    </dependencies>
<!--    配置java版本,解决java 不支持发行版本5错误-->
    <properties>
        <java.version>11</java.version>
        <maven.compiler.source>${java.version}</maven.compiler.source>
        <maven.compiler.target>${java.version}</maven.compiler.target>
    </properties>
</project>

(2)配置Runner和连接对象

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

<!--    告知spring容器在创建对象时需要扫描的包-->
    <context:component-scan base-package="dao"/>
    <context:component-scan base-package="service"/>
<!--    配置runner对象-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"><!--  scope="prototype"属性是多例属性,防止多个用户同时访问出现线程问题  -->
        <!--注入数据源-->
        <constructor-arg name="ds" ref="dataSource"/>
    </bean>
<!--    配置数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/travel"/>
        <property name="user" value="root"/>
        <property name="password" value="*******"/>
    </bean>
</beans>

(3)创建数据库

数据库结构

(4)创用户建实体类:

package domain;

import java.sql.Date;

public class User {
    private int uid;
    private String username;
    private String password;
    private String name;
    private Date birthday;
    private String sex;
    private String telephone;
    private String email;
    private String status;
    private String code;

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    @Override
    public String toString() {
        return "User{" +
                "uid=" + uid +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", name='" + name + '\'' +
                ", birthday=" + birthday +
                ", sex=" + sex +
                ", telephone='" + telephone + '\'' +
                ", email='" + email + '\'' +
                ", status='" + status + '\'' +
                ", code='" + code + '\'' +
                '}';
    }
}

(5)创建service业务逻辑接口:

package service;

import domain.User;

import java.util.List;

public interface UserService {
    /**
     * 查询所有
     */
    List<User> findAllUser();
    /**
     * 查询一个
     */
    User findUserById(int uid);
    /**
     * 插入一个
     */
    void saveUser(User user);
    /**
     * 更新
     */
    void updateUser (User user);
    /**
     * 删除
     */
    void  deleteUser(String username);
}

(6)创建service接口实现类

package service.impl;


import dao.UserDao;
import domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import service.UserService;
import java.util.List;

/**
 * 账户的业务层实现类
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired//自动按照类型注入数据
    private UserDao userDao;

    @Override
    public List<User> findAllUser() {
        return userDao.findAllUser();
    }

    @Override
    public User findUserById(int uid) {
        return userDao.findUserById(uid);
    }

    @Override
    public void saveUser(User user) {
        userDao.saveUser(user);
    }

    @Override
    public void updateUser(User user) {
        userDao.updateUser(user);
    }

    @Override
    public void deleteUser(String username) {
        userDao.deleteUser(username);
    }
}

(7)创建dao接口

package dao;

import domain.User;

import java.util.List;

public interface UserDao {

    /**
     * 查询所有
     */
    List<User> findAllUser();
    /**
     * 查询一个
     */
    User findUserById(int uid);
    /**
     * 插入一个
     */
    void saveUser(User user);
    /**
     * 更新
     */
    void updateUser (User user);
    /**
     * 删除
     */
    void  deleteUser(String username);

}

(8)创建dao接口实现类

package dao.impl;

import dao.UserDao;
import domain.User;
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("userDao")
public class UserDaoImpl implements UserDao {

    @Autowired//自动按照类型注入数据
    private QueryRunner runner;

    @Override
    public List<User> findAllUser() {
        List<User> list = null;
        try {
            list =  runner.query("select * from tab_user ",new BeanListHandler<User>(User.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public User findUserById(int uid) {
        User u = null;
        try {
            u = (User) runner.query("select * from tab_user where uid = ?",new BeanHandler<User>(User.class),uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return u;
    }

    @Override
    public void saveUser(User user) {
        try {
            runner.update("insert into tab_user(uid,username,password,name,birthday,sex,telephone,email,status,code) values(?,?,?,?,?,?,?,?,?,?)",user.getUid(),user.getUsername(),user.getPassword(),user.getName(),user.getBirthday(),user.getSex(),user.getTelephone(),user.getEmail(),user.getStatus(),user.getCode());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateUser(User user) {
        try {
            runner.update("update  tab_user set name=? where uid=?",user.getName(),user.getUid());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteUser(String username) {
        try {
            runner.update("delete from tab_user where username=? ",username);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

(9)项目目录结构

在这里插入图片描述

(10)测试

package test;

import domain.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.UserService;

import java.util.List;

public class UserServiceTest {
    @Test
    public void testFindAll() {
        //获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //获取业务层对象
        UserService us = ac.getBean("userService",UserService.class);
        //执行方法
        List<User> users = us.findAllUser();
        for (User user : users) {
            System.out.println(user);
        }
    }
    @Test
    public void testFindOne() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //获取业务层对象
        UserService us = ac.getBean("userService",UserService.class);
        //执行方法
        User user = us.findUserById(9);//将id为9的用户信息查询出来
        System.out.println(user.toString());
    }
    @Test
    public void testSave() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //获取业务层对象
        UserService us = ac.getBean("userService",UserService.class);
        //执行方法
        User user = new User();
        user.setUid(88);
        user.setBirthday(null);
        user.setCode("cm");
        user.setEmail("xjitcm@163.com");
        user.setName("小明");
        user.setPassword("123");
        user.setSex("男");
        user.setStatus("Y");
        user.setTelephone("18208276041");
        user.setUsername("dear");
        us.saveUser(user);
    }
    @Test
    public void testUpdate() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //获取业务层对象
        UserService us = ac.getBean("userService",UserService.class);
        //执行方法
        User user = new User();
        user.setUid(88);
        user.setBirthday(null);
        user.setCode("cc");
        user.setEmail("xjitcm@163.com");
        user.setName("xiaoming");
        user.setPassword("123");
        user.setSex("男");
        user.setStatus("Y");
        user.setTelephone("18208276041");
        user.setUsername("dear");
        us.updateUser(user);
    }
    @Test
    public void testDelete() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //获取业务层对象
        UserService us = ac.getBean("userService",UserService.class);
        us.deleteUser("dear");
    }
}

(11)测试分析

  • 查询所有用户
    在这里插入图片描述
  • 根据用户id查询用户
    在这里插入图片描述
  • 创建新的用户
    在这里插入图片描述
  • 修改用户信息
    在这里插入图片描述
  • 修改用户信息
    在这里插入图片描述

(12)测试结束



这篇关于spring+c3p0连接池+dbutils+mysql+junit测试基于注解实现ioc编程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程