利用spring+springMVC+JDBC+Mysql完成学生管理系统

本篇文章全程使用postman测试,使用json格式返回,可以看的更清楚,话不多说,让我们上代码

首先让我们看看 需要建的包以及类

使用 MVC开发模式  domain+service+mapper+controller 其中有用到一些自己封装的类所以建了utils和common包。

在开始之前,我们需要先往pom.xml中添加所需要使用的依赖

<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.dom4j/dom4j -->
    <dependency>
      <groupId>org.dom4j</groupId>
      <artifactId>dom4j</artifactId>
      <version>2.1.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.1.11.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.6</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.1.11.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.6</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.1.11.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.6</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.1.11.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.1.11.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
      <scope>provided</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
        <dependency>
          <groupId>javax.servlet.jsp</groupId>
          <artifactId>javax.servlet.jsp-api</artifactId>
          <version>2.3.3</version>
          <scope>provided</scope>
        </dependency>

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.33</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.22</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.2.8</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.json/json -->
    <dependency>
      <groupId>org.json</groupId>
      <artifactId>json</artifactId>
      <version>20230227</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2 -->
    <dependency>
      <groupId>com.alibaba.fastjson2</groupId>
      <artifactId>fastjson2</artifactId>
      <version>2.0.41</version>
    </dependency>

注意要填在dependencey里面,不然会报错。

springmvc.xml

<?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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
        <!-- 配置创建 spring 容器要扫描的包,初始化容器 -->

        <context:component-scan base-package="com.mashang"></context:component-scan>

        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
                <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
                <property name="url" value="jdbc:mysql://localhost:3306/learn?userSSL=false&amp;serverTimezone=Asia/Shanghai"></property>
                <property name="username" value="root"></property>
                <property name="password" value="123456"></property>
        </bean>
        <!--  初始化的时候自动生成一些对象,json自动转换  -->
        <mvc:annotation-driven></mvc:annotation-driven>
</beans>

这里我们注意一下,mapper层中写逻辑,然后使用service层调用,最后使用controller调用service的,这样可以让代码看起来整洁,清晰明了,每个层有自己该做的事

让我们先来看mapper层中的代码

@Repository
public class StudentMapper {

    @Resource(name = "dataSource")
    private DataSource dataSource;

    //查询学生列表信息
    //todo 分页
    public List<StudentList> findALl(Pagequary quary,String quaryName){
        Connection connection=null;
        PreparedStatement statement=null;
        ResultSet resultSet=null;

        StudentList studentList=new StudentList();

        List<StudentList> students=new ArrayList<>();

        Integer pageNum = quary.getPageNum();
        Integer pageSize = quary.getPageSize();

        System.out.println(pageNum);
        System.out.println(pageSize);


        String studentNo1 = studentList.getStudentNo();
        String name1 = studentList.getName();

        try {

            //第一步获取数据库对象 利用封装好的JDBC类来获取数据库对象
            connection=dataSource.getConnection();

            StringBuffer sql=new StringBuffer("SELECT * FROM student WHERE 1=1 ");

//            分页查询
            List<String> params=new ArrayList<>();
            List<Integer> page=new ArrayList<>();

//            根据student_no查询  (可省略)
//            if (studentNo1 !=null && !"".equals(studentNo1) ){
//                sql.append(" and t1.student_no = ?");
//                params.add(studentNo1);
//            }

            //根据名字模糊查询
            if (name1 !=null && !"".equals(name1) ){
                sql.append(" and t1.name like concat('%',?,'%')");
                params.add(name1);
            }
            sql.append(" order by create_time desc");

            page.add((pageNum-1)*pageSize);
            page.add(pageSize);

            sql.append(" limit " + (pageNum - 1) * pageSize + ","+pageSize);

            System.out.println(sql);

            //statement来存储sql语句
            statement= connection.prepareStatement(sql.toString());

            //最后使用resultSet来存储执行结果后的结果集
            resultSet=statement.executeQuery();

            //创建学生集合来存储循环出来的数据

            //当resultSet中有结果集时,一直循环
            while (resultSet.next()){
                int studentid = resultSet.getInt("student_id");
                String name = resultSet.getString("name");
                String studentNo = resultSet.getString("student_no");
                String sex = resultSet.getString("sex");
                int age = resultSet.getInt("age");
                String phone = resultSet.getString("phone");
                String createTime = resultSet.getString("create_time");
                String remark = resultSet.getString("remark");
                int classId = resultSet.getInt("class_id");

                students.add(new StudentList(studentid,name,studentNo,sex,phone,classId,age,createTime,remark));

                //获取总条数
//                int total= JDBCUtils.getTotal("student");

//                System.out.println(total);

//                Result.toGetTotal(total);

            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtils.close(connection,statement,resultSet);
        }
        return students;
    }


    //添加学生信息
    public int createStudent(Student student){

        //step1:获取前端传输的数据
        String name = student.getName();
        String studentNo = student.getStudentNo();
        Integer age=student.getAge();
        String phone = student.getPhone();
        String remark = student.getRemark();
        String sex = student.getSex();

        //step2:使用jdbc连接数据库
        Connection connection = null;
        PreparedStatement statement = null;

        int row=0;

        try {
            connection = dataSource.getConnection();
            System.out.println(dataSource);

            statement = connection.prepareStatement("insert into student(student_id,name,sex,age,student_No,phone,remark)values(null,?,?,?,?,?,?)");

            statement.setString(1,name);
            statement.setString(2,sex);

            if (age == null){
                statement.setObject(3,null);
            }else{
                statement.setInt(3,age);
            }

            statement.setString(4,studentNo);
            statement.setString(5,phone);
            statement.setString(6,remark);

            row = statement.executeUpdate();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtils.close(connection,statement);
        }
        return row;

    }

    //修改学生信息
    public int changeStudent(StudentParam studentParam){
        //通过实体类来获取数据
        Integer studentId =studentParam.getStudentId();
        String name = studentParam.getName();
        Integer age=studentParam.getAge();
        String sex = studentParam.getSex();
        String phone = studentParam.getPhone();
        String remark = studentParam.getRemark();

        int row=0;
        //连接数据库
        Connection connection = null;
        PreparedStatement statement = null;

        try {
            connection = dataSource.getConnection();


            statement = connection.prepareStatement("update student set name = ?,age = ?,sex = ?,phone = ?,remark = ? where student_id = ?");

            statement.setString(1,name);

            if (studentParam.getAge() != null){
                age = Integer.valueOf(studentParam.getAge());
                statement.setInt(2,age);
            }else {
                statement.setObject(2,age);
            }

            statement.setString(3,sex);
            statement.setString(4,phone);
            statement.setString(5,remark);

            if (studentId!=null){
                statement.setInt(6,studentId);
            }else {
                statement.setObject(6,studentId);
            }


            row = statement.executeUpdate();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtils.close(connection,statement);
        }
        return row;
    }

    //批量删除学生
    public int deleteBatch(List<Integer> studentIds) {

        int row=0;
        Connection connection=null;
        PreparedStatement preparedStatement = null;

        try {
            connection = dataSource.getConnection();

            StringBuffer sql = new StringBuffer("delete from student where student_id = ?");

            preparedStatement = connection.prepareStatement(sql.toString());

            //通过循环进行批量删除。
            for (int i=0;i<studentIds.size();i++){
                //addBatch方法可以进行批量操作
                preparedStatement.setInt(1,studentIds.get(i));
                preparedStatement.addBatch();
            }

            int[] rows=preparedStatement.executeBatch();
            for (int rowss:rows){
                if (rowss<0){
                    return 0;
                }
            }

//             row= preparedStatement.executeUpdate();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtils.close(connection,preparedStatement);
        }
        return  1;
    }
}

这代码应该很清晰明了,我就不解释了,如果有不懂的可以打在评论区!

 

JDBC

@Component
public class JDBCUtils {

    @Autowired
    private JDBCUtils jDBCUtils;

    @Autowired
    private DataSource dataSource;


    public static void  close(Connection connection, PreparedStatement statement, ResultSet resultSet){
       try {
           if (connection !=null){
               connection.close();
           }
           if (statement !=null){
               statement.close();
           }

           if (resultSet !=null){
               resultSet.close();
           }
       }catch (Exception e){
           e.printStackTrace();
       }
    }



    //分页
    public int getTotal(String tableName){
        int rowCount=0;
        Connection connection=null;
        PreparedStatement statement=null;
        ResultSet resultSet=null;

        try {

            System.out.println(dataSource);

            //获取数据库对象
            connection= jDBCUtils.dataSource.getConnection();

            StringBuffer sql=new StringBuffer("SELECT COUNT(*) FROM ");
            sql.append(tableName);

            System.out.println(sql);
            //利用statement存储sql语句
            statement=connection.prepareStatement(sql.toString());


            //执行上面statement中的sql语句
            resultSet=statement.executeQuery();


            //进行读取结果集的下一条数据
            resultSet.next();

            rowCount=resultSet.getInt(1);

        }catch (Exception e){
            System.out.println("获取分页失败");
            e.printStackTrace();
        }finally {
            JDBCUtils.close(connection,statement,resultSet);
        }
        return rowCount;
    }

    public static void  close(Connection connection, PreparedStatement statement){
        try {
            if (connection !=null){
                connection.close();
            }
            if (statement !=null){
                statement.close();
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

 Result

@Data
@NoArgsConstructor
public class Result {
    private Integer code;

    private String msg;

    private Object rows;

    private Integer total;

    public Result(Integer code, String msg, Object rows, Integer total) {
        this.code = code;
        this.msg = msg;
        this.rows = rows;
        this.total = total;
    }

    public Result(Integer code, String msg, Object rows) {
        this.code = code;
        this.msg = msg;
        this.rows = rows;
    }

    public Result(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    /**
     * data返回的是一个对象,rows返回的是一个数组。
     * rows=数组+分页+总条数
     */


    //进行封装
    public static Result getResult(Integer code,String msg,Object rows){
        return new Result(code,msg,rows);
    }

    public static Result SuccessResult(String msg){
        return new Result(200,"操作成功");
    }

    public static Result errorResult(String msg){
        return new Result(500,"操作失败");
    }

    public static Result toResult(int row){
        return row > 0 ? Result.SuccessResult("操作成功") : Result.errorResult("操作失败");
    }

    //进行封装
    public static Result getResult(Integer code,String msg,Object rows,Integer total){
        return new Result(code,msg,rows,total);
    }
}

Pagequary

 

Student

 

StudentList 

StudentParam

 

上面都是一些基本的实体类和包装类。下面是service层中调用mapper层。

@Service
public class StudentService {
    //自动注入  service层中调用mapper层中的逻辑
    @Autowired
    private StudentMapper studentMapper;

    //查询学生列表信息
    public List<StudentList> findAll(Pagequary quary, String quaryName){
        //需要将 mapper层中的方法返回到service层  然后Controller层再从service层中进行调用
     return studentMapper.findALl(quary,quaryName);
    }

    //添加学生信息
    public int createStudent(Student student){
    return studentMapper.createStudent(student);
    }

    //修改学生信息
    public int changeStudent(StudentParam studentParam){
        return studentMapper.changeStudent(studentParam);
    }

    //批量删除学生信息
    public int deleteBatch(List<Integer> studentIds){
     return studentMapper.deleteBatch(studentIds);
    }
}

 controller层中调用service层的逻辑

**
 * 1.接受客户端传输的数据,
 * 2.传输数据,调用service层 进行逻辑处理
 * 3.响应数据
 * */

// ResponseBody和Controller   @ResponseBody+@Controller=@RestController
    @RestController
@RequestMapping("/student")
public class StudentController {
    //将service对象注入到Controller层
    //因为数据类型默认值为空,所以需要引入@Autowired注解
    @Autowired
    private StudentService studentService;//引用数据类型,默认值为null


    @Autowired
    private JDBCUtils jDBCUtils;

    //查询学生列表信息
    @GetMapping("/list")
    public Result findAll(Pagequary quary,String quaryName){
        int total = jDBCUtils.getTotal("student");
        return  Result.getResult(200,"查询成功",studentService.findAll(quary,quaryName),total);

    }
    //添加学生信息
    @PostMapping("/add")
    public Result createStudent(@RequestBody Student student){
        return Result.toResult(studentService.createStudent(student));
    }

    //修改学生信息
    @PutMapping("/update")
    public Result changeStudent(@RequestBody StudentParam studentParam){
        return Result.toResult(studentService.changeStudent(studentParam));
    }

    //根据学生id批量删除学生详情信息
    @DeleteMapping("/{studentIds}")
    public Result deleteBatch(@PathVariable List<Integer> studentIds){
        int row = studentService.deleteBatch(studentIds);
        return Result.toResult(row);
    }
}

 代码中还有许多可以优化的地方,需要注意引入依赖和配置文件的完整,以后还会更新很多有关学习java的文章,希望对你有帮助。

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值