凯哥学堂

搜索

凯哥学堂

依赖注入实现增删查改

2018-11-7 18:31| 发布者: 可可| 查看: 1| 评论: 0

凯哥学堂 首页 资讯 学习笔记 JavaEE 查看内容

声明:本栏目所使用的素材都是凯哥学堂VIP学员所写,学员有权匿名,对文章有最终解释权;凯哥学堂旨在促进VIP学员互相学习的基础上公开笔记。

使用依赖注入做一个增删查改的小例题

pom.xml文件配置如下:

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.39</version>
        </dependency>
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20160810</version>
        </dependency>
    </dependencies>

Spring配置文件内容如下:

<?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:p="http://www.springframework.org/schema/p"
       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:annotation-config/>
    <!-- 指定哪些包下的类受可以让Spring通过注解来管理 -->
    <context:component-scan base-package="org.zero01"/>

    <!-- 配置数据源对象 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
          p:driverClass="com.mysql.jdbc.Driver"
          p:jdbcUrl="jdbc:mysql:///school"
          p:user="root"
          p:password="your_password"
          p:maxPoolSize="10"
          p:minPoolSize="1"
          p:loginTimeout="2000"
    />

</beans>

首先是接口代码:

package org.zero01.dao;

import org.zero01.pojo.Student;

import java.util.List;

public interface DAO {

    public int insert(Student student) throws Exception;
    public int delete(int sid) throws Exception;
    public List<Student> selectAll() throws Exception;
    public int update(Student student) throws Exception;
}



package org.zero01.service;

import org.zero01.pojo.Student;

import java.util.List;

public interface Service {

    public int enterSchool(Student student);
    public int dropOut(int sid);
    public List<Student> getStudents();
    public int updateData(Student student);

}



package org.zero01.view;

import org.zero01.pojo.Student;

import java.util.List;

public interface View {

    public int enterSchool(Student student);
    public int dropOut(int sid);
    public List<Student> getStudents();
    public int updateData(Student student);
}

然后是具体的实现类代码,StudentDAO类:

package org.zero01.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.zero01.pojo.Student;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Component("stuDAO")
public class StudentDAO implements DAO {

    @Autowired
    private DataSource dataSource;

    public int insert(Student student) throws Exception {

        Connection connection = null;

        try {

            connection = dataSource.getConnection();
            String sql = "INSERT INTO student(sname,age,sex,address) VALUES (?,?,?,?)";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, student.getSname());
            preparedStatement.setInt(2, student.getAge());
            preparedStatement.setString(3, student.getSex());
            preparedStatement.setString(4, student.getAddress());

            int row = preparedStatement.executeUpdate();

            if (row > 0) {
                return row;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            connection.close();
        }

        return 0;
    }

    public int delete(int sid) throws Exception {

        Connection connection = null;

        try {

            connection = dataSource.getConnection();
            String sql = "DELETE FROM student WHERE sid=?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, sid);

            int row = preparedStatement.executeUpdate();

            if (row > 0) {
                return row;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            connection.close();
        }

        return 0;
    }

    public List<Student> selectAll() throws Exception {
        Connection connection = null;

        try {

            connection = dataSource.getConnection();
            String sql = "select * from student";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            ResultSet resultSet = preparedStatement.executeQuery();

            List<Student> students = new ArrayList<Student>();
            while (resultSet.next()) {
                Student student = new Student();
                student.setSid(resultSet.getInt("sid"));
                student.setSname(resultSet.getString("sname"));
                student.setSex(resultSet.getString("sex"));
                student.setAddress(resultSet.getString("address"));
                students.add(student);
            }
            return students;

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            connection.close();
        }

        return null;
    }

    public int update(Student student) throws Exception {
        Connection connection = null;

        try {

            connection = dataSource.getConnection();
            String sql = "UPDATE student SET sname=?,age=?,sex=?,address=? WHERE sid=?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, student.getSname());
            preparedStatement.setInt(2, student.getAge());
            preparedStatement.setString(3, student.getSex());
            preparedStatement.setString(4, student.getAddress());
            preparedStatement.setInt(5, student.getSid());

            int row = preparedStatement.executeUpdate();

            if (row > 0) {
                return row;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            connection.close();
        }

        return 0;
    }
}

SchoolService代码:

package org.zero01.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.zero01.dao.DAO;
import org.zero01.pojo.Student;

import java.util.List;

@Component("schoolService")
public class SchoolService implements Service {

    @Autowired
    private DAO dao;

    public int enterSchool(Student student) {
        try {
            return dao.insert(student);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public int dropOut(int sid) {
        try {
            return dao.delete(sid);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public List<Student> getStudents() {
        try {
            return dao.selectAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public int updateData(Student student) {
        try {
            return dao.update(student);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}

SchoolAction代码:

package org.zero01.view;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.zero01.pojo.Student;
import org.zero01.service.Service;

import java.util.List;

@Component("stuAction")
public class SchoolAction implements View {

    @Autowired
    private Service schoolService;

    public int enterSchool(Student student) {
        return schoolService.enterSchool(student);
    }

    public int dropOut(int sid) {
        return schoolService.dropOut(sid);
    }

    public List<Student> getStudents() {
        return schoolService.getStudents();
    }

    public int updateData(Student student) {
        return schoolService.updateData(student);
    }
}

从以上的代码可以看到,我们没有在哪一个类里写了关于任何实例化对象的代码,而是把实例化这项工作交给Spring容器去帮我们完成,这样每个类都不需要去管理、维护自己的依赖对象,只需要完成自己业务代码即可,这样弱化了类与类之间的依赖,让代码的复杂度降低,每个类都只需要维护自己的业务代码即可,这是Spring的IOC模块给我们带来的好处。而且每个类都依赖的是接口,而不是具体的实现类,符合依赖倒转原则,不会导致代码紧耦合,当具体的实现类被替换时,不会影响到其他类。

测试代码:

package org.zero01;

import org.json.JSONObject;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.zero01.view.View;
import org.zero01.pojo.Student;

import java.util.HashMap;
import java.util.Map;

public class Test {

    public static void main(String[] args) {

        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");

        View view = (View) app.getBean("stuAction");
        Student student = (Student) app.getBean("student");

        System.out.println("enterSchool() 影响行数:" + view.enterSchool(student));
        System.out.println("dropOut() 影响行数:" + view.dropOut(25));

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("studentList", view.getStudents());
        map.put("length", view.getStudents().size());
        System.out.println(new JSONObject(map));

        student.setSname("小刚");
        student.setAddress("长沙");
        student.setAge(18);
        student.setSid(29);
        System.out.println("updateData() 影响行数:" + view.updateData(student));
    }
}

运行结果:

enterSchool() 影响行数:1
dropOut() 影响行数:1
{
  "studentList": [
    {
      "address": "南京",
      "sname": "小明",
      "sex": "",
      "age": 0,
      "sid": 26
    },
    {
      "address": "南京",
      "sname": "












关注我们


微信

微博

QQ