您现在的位置是:首页 > 正文

简单的spring 数据库编程

2024-04-01 01:25:18阅读 3

目录

新建maven工程

配置pom.xml,导入相关的包

项目结构图

daomain层

Student

dao层

IstudentDao

StudentDaoImpl

serivice层

IStudentService

controller层

StudentController

bean.xml

运行StudentController


新建maven工程

配置pom.xml,导入相关的包

<?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>org.example</groupId>
    <artifactId>studentManagementSystem</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!-- spring包-->
        <!-- <https://mvnrepository.com/artifact/org.springframework/spring-context> -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.20</version>
        </dependency>

        <!-- mysql数据库驱动包 -->
        <!-- <https://mvnrepository.com/artifact/mysql/mysql-connector-java> -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>

        <!-- jdbc包 -->
        <!-- <https://mvnrepository.com/artifact/org.springframework/spring-jdbc> -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.23</version>
        </dependency>

        <!-- spring事务包 -->
        <!-- <https://mvnrepository.com/artifact/org.springframework/spring-tx> -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.3.23</version>
        </dependency>

    </dependencies>
</project>

项目结构图

daomain层

Student

package com.ili.daomain;

public class Student {
    //账号/学号
    private String studentID;
    //密码
    private String password;
    //姓名
    private String name;
    //性别,0是女,1是男
    private boolean gender;
    private String college;
    private String major;

    public String getStudentID() {
        return studentID;
    }

    public String getPassword() {
        return password;
    }

    public String getName() {
        return name;
    }

    public boolean isGender() {
        return gender;
    }

    public String getCollege() {
        return college;
    }

    public String getMajor() {
        return major;
    }

    public void setStudentID(String studentID) {
        this.studentID = studentID;
    }

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

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

    public void setGender(boolean gender) {
        this.gender = gender;
    }

    public void setCollege(String college) {
        this.college = college;
    }

    public void setMajor(String major) {
        this.major = major;
    }

    public Student(String studentID, String password, String name, boolean gender, String college, String major) {
        this.studentID = studentID;
        this.password = password;
        this.name = name;
        this.gender = gender;
        this.college = college;
        this.major = major;
    }

    public Student() {

    }

    @Override
    public String toString() {
        return "Student{" +
                "studentID='" + studentID + '\\'' +
                ", password='" + password + '\\'' +
                ", name='" + name + '\\'' +
                ", gender=" + gender +
                ", college='" + college + '\\'' +
                ", major='" + major + '\\'' +
                '}';
    }
}

dao层

IstudentDao

package com.ili.dao;

import com.ili.daomain.Student;

public interface IStudentDao {
    //增
    void addStudent(Student s);
    //删
    void deleteStudentByID(String ID);
    //改
    void updateStudent(Student s);
    //查
    Student getStudentByID(String ID);
}

StudentDaoImpl

package com.ili.dao.Impl;

import com.ili.dao.IStudentDao;
import com.ili.daomain.Student;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class StudentDaoImpl implements IStudentDao {
    private JdbcTemplate jdbcTemplate;
    @Override
    public void addStudent(Student s) {
        String sql = "insert into student(studentID, password, name, gender, college, major) values(?, ?, ?, ?, ?, ?)";
        jdbcTemplate.update(sql, s.getStudentID(), s.getPassword(), s.getName(), s.isGender(), s.getCollege(), s.getMajor());
    }

    @Override
    public void deleteStudentByID(String studentID) {
        String sql = "delete from student where studentID=?";
        jdbcTemplate.update(sql, studentID);
    }

    @Override
    public void updateStudent(Student s) {
        String sql = "update student set password=?, name=?, gender=?, college=?, major=? where studentID=?";
        jdbcTemplate.update(sql, s.getPassword(), s.getName(), s.isGender(), s.getCollege(), s.getMajor(), s.getStudentID());
    }

    @Override
    public Student getStudentByID(String ID) {
        List<Student> students = null;

        String sql = "select * from student where studentID=?";
        students =  jdbcTemplate.query(sql, new Object[]{ID}, new BeanPropertyRowMapper<>(Student.class));
        if (students != null && students.size()>=1){
            return students.get(0);
        }
        else {
            return null;
        }
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
}

serivice层

IStudentService

package com.ili.serivice;

import com.ili.daomain.Student;

public interface IStudentSerivice {
    //验证密码
    boolean checkPassword(String studentID, String password);
    //增
    void addStudent(String studentID, String password, String name, String gender, String college, String major);
    //删
    void deleteStudentByID(String ID);
    //改
    void updateStudent(String studentID, String password, String name, String gender, String college, String major);
    //查
    Student getStudentByID(String ID);
}

StudentService

package com.ili.serivice.Impl;

import com.ili.dao.Impl.StudentDaoImpl;
import com.ili.daomain.Student;
import com.ili.serivice.IStudentSerivice;

import java.sql.ParameterMetaData;

public class StudentService implements IStudentSerivice {
    private StudentDaoImpl studentDao;

    @Override
    public boolean checkPassword(String studentID, String password) {
        Student student =  studentDao.getStudentByID(studentID);

        if (student==null) {
            return false;
        }
        else if (password.equals(student.getPassword())){

            return true;
        }
        else{
            return false;
        }

    }
    @Override
    public void addStudent(String studentID, String password, String name, String gender_s, String college, String major) {
        boolean gender = true;
        if (gender_s.equals("女"))gender = false;
        Student student = new Student(studentID, password, name, gender, college, major);

        studentDao.addStudent(student);
    }
    @Override
    public void deleteStudentByID(String ID) {
        studentDao.deleteStudentByID(ID);
    }
    @Override
    public void updateStudent(String studentID, String password, String name, String gender_s, String college, String major) {
        boolean gender = true;
        if (gender_s.equals("女"))gender = false;
        Student student = new Student(studentID, password, name, gender, college, major);
        studentDao.updateStudent(student);
    }

    @Override
    public Student getStudentByID(String studentID) {
        return studentDao.getStudentByID(studentID);
    }

    public void setStudentDao(StudentDaoImpl studentDao) {
        this.studentDao = studentDao;
    }

}

controller层

StudentController

package com.ili.controller;

import com.ili.dao.IStudentDao;
import com.ili.daomain.Student;
import com.ili.serivice.IStudentSerivice;
import com.ili.serivice.Impl.StudentService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;
import java.util.Scanner;

public class StudentController {
    private static IStudentSerivice studentSerivice;

    static {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        studentSerivice = (StudentService) context.getBean("studentService");
    }

    public static void main(String[] args) {
        System.out.println("欢迎使用学生管理系统");
        boolean loggedIn = login();

        if (loggedIn) {
            while (true) {
                System.out.println("请选择操作:");
                System.out.println("1. 添加学生");
                System.out.println("2. 删除学生");
                System.out.println("3. 更新学生信息");
                System.out.println("4. 查询学生信息");
                System.out.println("0. 退出");

                Scanner scanner = new Scanner(System.in);
                int choice = scanner.nextInt();

                switch (choice) {
                    case 1:
                        addStudent();
                        break;
                    case 2:
                        deleteStudent();
                        break;
                    case 3:
                        updateStudent();
                        break;
                    case 4:
                        queryStudent();
                        break;
                    case 0:
                        System.out.println("退出程序。");
                        System.exit(0);
                        break;
                    default:
                        System.out.println("无效选项,请重新输入。");
                }
            }
        }
    }

    //登录
    public static boolean login(){
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入用户名:");
        String studentID = scanner.next();
        System.out.println("请输入密码:");
        String password = scanner.next();

        if (studentSerivice.checkPassword(studentID, password)){
            System.out.println("登陆成功!");
            return true;
        }
        else {
            System.out.println("账号或密码错误!");
            return false;
        }

    }

    // 添加新学生
    public static void addStudent() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入学生ID:");
        String studentID = scanner.next();
        System.out.println("请输入密码:");
        String password = scanner.next();
        System.out.println("请输入姓名:");
        String name = scanner.next();
        System.out.println("请输入性别(男,女):");
        String gender = scanner.next();
        System.out.println("请输入学院:");
        String college = scanner.next();
        System.out.println("请输入专业:");
        String major = scanner.next();

        studentSerivice.addStudent(studentID, password, name, gender, college, major);
        System.out.println("学生添加成功!");
    }

    // 删除学生记录
    public static void deleteStudent() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要删除的学生ID:");
        String studentID = scanner.next();

        studentSerivice.deleteStudentByID(studentID);
        System.out.println("学生删除成功!");
    }

    // 更新学生信息
    public static void updateStudent() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要更新的学生ID:");
        String studentID = scanner.next();

        Student student = studentSerivice.getStudentByID(studentID);

        if (student != null) {
            System.out.println("请输入新密码:");
            String newPassword = scanner.next();
            System.out.println("请输入新姓名:");
            String newName = scanner.next();
            System.out.println("请输入新性别(男,女):");
            String newGender = scanner.next();
            System.out.println("请输入新学院:");
            String newCollege = scanner.next();
            System.out.println("请输入新专业:");
            String newMajor = scanner.next();

            studentSerivice.updateStudent(studentID, newPassword, newName, newGender, newCollege, newMajor);
            System.out.println("学生信息更新成功!");
        } else {
            System.out.println("未找到具有指定ID的学生。");
        }
    }

    // 查询学生信息
    public static void queryStudent() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要查询的学生ID:");
        String studentID = scanner.next();

        Student student = studentSerivice.getStudentByID(studentID);

        if (student != null) {
            System.out.println("学生信息:");
            System.out.println("ID:" + student.getStudentID());
            System.out.println("姓名:" + student.getName());
            System.out.println("性别:" + (student.isGender() ? "男性" : "女性"));
            System.out.println("学院:" + student.getCollege());
            System.out.println("专业:" + student.getMajor());
        } else {
            System.out.println("未找到具有指定ID的学生。");
        }
    }

}

bean.xml

注意要把数据库的配置换成自己的

<beans xmlns="<http://www.springframework.org/schema/beans>"
       xmlns:xsi="<http://www.w3.org/2001/XMLSchema-instance>"
       xsi:schemaLocation="<http://www.springframework.org/schema/beans>
    <http://www.springframework.org/schema/beans/spring-beans.xsd>">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!-- 数据库驱动 -->
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <!-- 连接数据库url -->
        <property name="url" value="jdbc:mysql://localhost:3306/studentManagementSystem"/>
        <property name="username" value="root"/> <!-- 连接数据库用户名 -->
        <property name="password" value="111111"/> <!-- 连接数据库密码 -->
    </bean>

    <bean id="jdbcTemplate"   class="org.springframework.jdbc.core.JdbcTemplate"  scope="prototype">
        <!-- 默认必须使用数据源  -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--数据库学生表的管理,多例-->
    <bean id="studentDao" class="com.ili.dao.Impl.StudentDaoImpl"  scope="prototype">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>

    <!--学生信息服务-->
    <bean id="studentService" class="com.ili.serivice.Impl.StudentService" scope="prototype">
        <property name="studentDao" ref="studentDao"/>
    </bean>

</beans>

运行StudentController

网站文章