0


(附完整代码)Java学生信息管理系统结合图形界面展示

碰到问题欢迎私信我,谢谢关注~

一.程序结构设计

利用maven对项目进行管理简化了手动jar包导入的过程。采用了类似三层架构的思想将业务逻辑层,数据访问层和表现层分包编写。在数据访问层用Mybatis简化了JDBC代码的书写,采取mapper代理开发让Mybatis更加简单。在业务逻辑层编写了增删改查注册登录方法可以供表现层单独调用。在表现层以图形界面形式展示各个功能,捕获用户操作对数据库进行处理。

二.项目图片展示

1.登录界面

用户可以填写账号密码进行注册,注册时会检测数据库中是否存在相同账号,如果已存在则会拦截注册并跳出提醒窗口,反之注册成功。登录和注册窗口可以相互跳转。

2.注册界面

可拦截重复注册数据库中已存在的账号,密码不检查。按注册未输入账号密码会跳出相应提醒对话框,如果输入账号在数据库已存在也会跳出相应提醒对话框。按重置会清空输入的账号和密码,按返回会跳转回登录界面。

3.管理后台主界面

(1)查询所有学生

可以点击查看按钮查看数据库已存在的所有学生学生信息

(2)通过学号查询单个学生

可以输入学号查询存在的学生,如果查询的学生不存在则跳出提醒对话框

(3)删除单个学生

可以单击选中某条数据再按删除按钮删除学生

4.添加学生界面

点击添加学生按钮可弹出新窗口录入学生数据,可检查学号是否已存在,如果存在则会拦截本次添加,否则将录入的数据存入数据库中。

5.修改学生界面

需要在主界面单击选中某条学生然后点击修改按钮,可跳出一个修改界面,在界面中会回显该学生所有数据

三.项目代码

一.在数据库中建表

(1)学生信息表

CREATE database studentMessage;

CREATE TABLE studentAll(
sid INT PRIMARY KEY,
name VARCHAR(5),
age INT,
major VARCHAR(5),
grade VARCHAR(5),
loveSubj VARCHAR(5)
);

SELECT * FROM studentAll;

(2)登录用户表

CREATE TABLE tb_user(
id INT PRIMARY KEY,
username VARCHAR(20),
password varchar(20)
);
SELECT * from tb_user;

二.Data对象(Pojo)

(1)学生类

package pojo;
/**
 * @author 观止
 */
public class Student {
    private int sid;
    private String name;
    private int age;
    private String major;
    private String grade;
    private String loveSubj;

    public Student() {
    }

    public Student(int sid, String name, int age, String major, String grade, String loveSubj) {
        this.sid = sid;
        this.name = name;
        this.age = age;
        this.major = major;
        this.grade = grade;
        this.loveSubj = loveSubj;
    }

    public int getSid() {
        return sid;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getMajor() {
        return major;
    }

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

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }

    public String getloveSubj() {
        return loveSubj;
    }

    public void setloveSubj(String loveSubj) {
        this.loveSubj = loveSubj;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sid=" + sid +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", major='" + major + '\'' +
                ", grade='" + grade + '\'' +
                ", loveSubj='" + loveSubj + '\'' +
                '}';
    }
}

(2)用户类

package pojo;
/**
 * @author 观止
 */
public class User {

    private Integer id;
    private String username;
    private String password;

    public User() {

    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    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;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

三.mapper代理层

(1)StudentMapper

import pojo.Student;

import java.util.List;
/**
 * @author 观止
 */
public interface StudentMapper {

    //查询所有学生
    List<Student> selectAll();

    //添加学生
    void add(Student student);

    //验证学号和姓名删除学生
    void delete(int id);

    //修改学生信息
    void update(Student student);

    //查询单个学生
    Student selectBySid(int sid);

}

(2)UserMapper(sql语句比较短用的注解开发)

package mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import pojo.User;
/**
 * @author 观止
 */
public interface UserMapper {

    @Select("select * from tb_user where username=#{username} and password=#{password}")
    User select(@Param("username") String username, @Param("password") String password);

    @Insert("insert into tb_user (id,username,password) values(null,#{username},#{password})")
    void insert(User user);

    @Select("select * from tb_user where username=#{username}")
    User selectByUsername(String username);

}

四.service层

(1)studentService

package service;

import mapper.StudentMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import pojo.Student;
import util.SqlSessionFactoryUtils;
import java.util.List;
/**
 * @author 观止
 */
public class studentService {
    SqlSessionFactory sqlSessionFactory=SqlSessionFactoryUtils.getSqlSessionFactory();

    //查询所有学生
    public  List<Student> selectAll(){
        SqlSession sqlSession = sqlSessionFactory.openSession();

        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

        List<Student> students = mapper.selectAll();

        sqlSession.close();

        return students;
    }

   //添加学生
    public  void add(Student student){

        SqlSession sqlSession = sqlSessionFactory.openSession();

        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

        mapper.add(student);

        sqlSession.commit();

        sqlSession.close();
    }

   //删除学生
    public  void delete(int sid){
        SqlSession sqlSession = sqlSessionFactory.openSession();

        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

        mapper.delete(sid);

        sqlSession.commit();

        sqlSession.close();
    }

    //修改学生
    public void update(Student student){
        SqlSession sqlSession = sqlSessionFactory.openSession();

        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

        mapper.update(student);

        sqlSession.commit();

        sqlSession.close();
    }
//通过学号查询学生
    public Student selectBySid(int sid){
        SqlSession sqlSession = sqlSessionFactory.openSession();

        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

        Student student = mapper.selectBySid(sid);

        return student;
    }

}

(2)userService

package service;

import mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import pojo.User;
import util.SqlSessionFactoryUtils;
/**
 * @author 观止
 */
public class userService {

    SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
//检查用户名是否重复
    public boolean check(String username) {

        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user = mapper.selectByUsername(username);

        return user==null?true:false;

    }
//注册账号
    public void regiser(User user) {

        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        mapper.insert(user);

        sqlSession.commit();

        sqlSession.close();

    }
//登录
    public Boolean login(String username, String password) {
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user = mapper.select(username, password);

        sqlSession.close();

        return user != null ? true : false;

    }

}

五.图形界面GUI层

(1)LoginView(登录界面)

package GUITest;

import service.userService;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

/**
 * @author 观止
 */
public class LoginView extends JFrame {

    private JPanel contentPane;
    private JTextField usernameText;
    private JTextField passwordText;
    private userService userservice = new userService();

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            try {
                LoginView frame = new LoginView();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * Create the frame.
     */
    public LoginView() {
        setTitle("欢迎登录");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setBounds(100, 100, 380, 250);
        setLocationRelativeTo(null);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JLabel lblNewLabel = new JLabel("账号:");
        lblNewLabel.setBounds(92, 50, 50, 15);
        contentPane.add(lblNewLabel);

        usernameText = new JTextField();
        usernameText.setBounds(131, 47, 160, 21);
        contentPane.add(usernameText);
        usernameText.setColumns(10);

        JLabel lblNewLabel_1 = new JLabel("密码:");
        lblNewLabel_1.setBounds(92, 93, 43, 15);
        contentPane.add(lblNewLabel_1);

        passwordText = new JTextField();
        passwordText.setBounds(131, 90, 160, 21);
        contentPane.add(passwordText);
        passwordText.setColumns(10);

        //注册
        JButton registerBtn = new JButton("注册");
        registerBtn.addActionListener(e -> {

            RegisterView view = new RegisterView();
            view.setVisible(true);
            dispose();

        });
        registerBtn.setBounds(210, 150, 74, 23);
        contentPane.add(registerBtn);

        //登录
        JButton LoginBtn = new JButton("登录");
        LoginBtn.addActionListener(e -> {
            stulogin();
        });
        LoginBtn.setBounds(115, 150, 74, 23);
        contentPane.add(LoginBtn);

    }

    public void stulogin() {
        if (userservice.login(usernameText.getText(), passwordText.getText())) {
            JOptionPane.showMessageDialog(null, "登录成功!", "提示消息", JOptionPane.WARNING_MESSAGE);
            //关闭当前界面
            dispose();
            UserListView view = new UserListView();
            view.setVisible(true);
        } else if (usernameText.getText().isEmpty() && passwordText.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "请输入用户名和密码!", "提示消息", JOptionPane.WARNING_MESSAGE);
        } else if (usernameText.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "请输入用户名!", "提示消息", JOptionPane.WARNING_MESSAGE);
        } else if (passwordText.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "请输入密码!", "提示消息", JOptionPane.WARNING_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(null, "用户名或者密码错误!\n请重新输入", "提示消息", JOptionPane.ERROR_MESSAGE);
            usernameText.setText("");
            passwordText.setText("");
        }
    }

}

(2)RegisterVie(注册界面)

package GUITest;

import pojo.User;
import service.userService;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

/**
 * @author 观止
 */
public class RegisterView extends JFrame {

    private JPanel contentPane;
    private JTextField usernameText;
    private JTextField passwordText;
    private userService userservice = new userService();

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            try {
                RegisterView frame = new RegisterView();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * Create the frame.
     */
    public RegisterView() {
        setTitle("欢迎注册");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setBounds(100, 100, 380, 250);
        setLocationRelativeTo(null);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JLabel lblNewLabel = new JLabel("账号:");
        lblNewLabel.setBounds(92, 50, 50, 15);
        contentPane.add(lblNewLabel);

        usernameText = new JTextField();
        usernameText.setBounds(131, 47, 160, 21);
        contentPane.add(usernameText);
        usernameText.setColumns(10);

        JLabel lblNewLabel_1 = new JLabel("密码:");
        lblNewLabel_1.setBounds(92, 93, 43, 15);
        contentPane.add(lblNewLabel_1);

        passwordText = new JTextField();
        passwordText.setBounds(131, 90, 160, 21);
        contentPane.add(passwordText);
        passwordText.setColumns(10);

        //注册
        JButton registerBtn = new JButton("注册");
        registerBtn.addActionListener(e -> {

            String username = usernameText.getText();
            String password = passwordText.getText();

            if (username == null || "".equals(username)) {
                JOptionPane.showMessageDialog(contentPane, "请输入账号", "系统提示", JOptionPane.WARNING_MESSAGE);
            } else if (password == null || "".equals(password)) { JOptionPane.showMessageDialog(contentPane, "请输入密码", "系统提示", JOptionPane.WARNING_MESSAGE);

            } else if (userservice.check(username)) {
                if (username.isEmpty() && password.isEmpty()) {
                    JOptionPane.showMessageDialog(null, "请输入用户名和密码!", "提示消息", JOptionPane.WARNING_MESSAGE);
                } else {
                    User user = new User();
                    user.setUsername(username);
                    user.setPassword(password);
                    userservice.regiser(user);
                    JOptionPane.showMessageDialog(null, "注册成功!", "提示消息", JOptionPane.WARNING_MESSAGE);
                    LoginView view = new LoginView();
                    view.setVisible(true);
                    dispose();
                }
            } else {
                JOptionPane.showMessageDialog(contentPane, "用户名已存在", "系统提示", JOptionPane.WARNING_MESSAGE);
                usernameText.setText("");
                passwordText.setText("");
            }

        });
        registerBtn.setBounds(115, 150, 74, 23);
        contentPane.add(registerBtn);

        //重置
        JButton LoginBtn = new JButton("重置");
        LoginBtn.addActionListener(e -> {
            usernameText.setText("");
            passwordText.setText("");
        });
        LoginBtn.setBounds(210, 150, 74, 23);
        contentPane.add(LoginBtn);

        //返回
        JButton returnBtn = new JButton("返回");
        returnBtn.addActionListener(e -> {
            LoginView view = new LoginView();
            view.setVisible(true);
            dispose();
        });
        returnBtn.setBounds(160, 180, 74, 23);
        contentPane.add(returnBtn);

    }

}

(3)UserListView(系统主界面)

package GUITest;

import pojo.Student;
import service.studentService;

import java.awt.EventQueue;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;

/**
 * @author 观止
 */
public class UserListView extends JFrame {

    private JPanel contentPane;
    private JTable table;
    private JTextField sidText;

    private studentService service = new studentService();

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            try {
                UserListView frame = new UserListView();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * Create the frame.
     */
    public UserListView() {

        setTitle("学生信息管理系统");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 600, 337);
        setLocationRelativeTo(null);

        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(10, 39, 564, 232);
        contentPane.add(scrollPane);

        Object[] columns = {"学号", "名字", "年龄", "专业", "班级", "偏爱学科"};
        Object[][] data = null;
        DefaultTableModel model = new DefaultTableModel(data, columns);
        table = new JTable(model);
        //加载学生数据
        load(null);
        scrollPane.setViewportView(table);

        JLabel lblNewLabel = new JLabel("学号");
        lblNewLabel.setBounds(10, 10, 42, 15);
        contentPane.add(lblNewLabel);

        sidText = new JTextField();
        sidText.setBounds(44, 8, 115, 21);
        contentPane.add(sidText);
        sidText.setColumns(10);

        //查看按钮
        JButton searchBtn = new JButton("查看");
        searchBtn.addActionListener(e -> load(sidText.getText()));

        searchBtn.setBounds(300, 8, 63, 23);
        contentPane.add(searchBtn);

        //搜索学生
        JButton searchBtn1 = new JButton("搜索");
        searchBtn1.addActionListener(e -> search(Integer.parseInt(sidText.getText())));

        searchBtn1.setBounds(169, 8, 63, 23);
        contentPane.add(searchBtn1);

        //添加按钮
        JButton addBtn = new JButton("添加");
        addBtn.addActionListener(e -> {
            AddView view = new AddView();
            view.setVisible(true);
        });
        addBtn.setBounds(365, 8, 63, 23);

        contentPane.add(addBtn);

        //修改按钮
        JButton updateBtn = new JButton("修改");
        updateBtn.addActionListener(e -> {
            // 获取选中行
            int row = table.getSelectedRow();
            if (row < 0) {
                JOptionPane.showMessageDialog(contentPane, "请选择一条记录", "系统提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            int id = Integer.valueOf(table.getValueAt(row, 0).toString());
            UpdateView view = new UpdateView(id);
            view.setVisible(true);

        });
        updateBtn.setBounds(438, 8, 63, 23);

        //删除按钮
        JButton deleteBtn = new JButton("删除");
        deleteBtn.addActionListener(e -> {
            // 获取选中行
            int row = table.getSelectedRow();
            if (row < 0) {
                JOptionPane.showMessageDialog(contentPane, "请选择一条记录", "系统提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            int result = JOptionPane.showConfirmDialog(contentPane, "确认删除该学生吗?", "提示",
                    JOptionPane.YES_NO_OPTION);
            if (result == 0) {
                int sid = Integer.valueOf(table.getValueAt(row, 0).toString());
                service.delete(sid);
                JOptionPane.showMessageDialog(contentPane, "删除成功!");
                load(null);
            }
        });
        deleteBtn.setBounds(511, 8, 63, 23);
        contentPane.add(deleteBtn);
        contentPane.add(updateBtn);
    }

    // 填充表格数据
    public void load(String sid) {
        List<Student> list = service.selectAll();
        DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
        tableModel.setRowCount(0);
        // 填充数据
        for (Student item : list) {
            String[] arr = new String[6];
            arr[0] = item.getSid() + "";
            arr[1] = item.getName();
            arr[2] = String.valueOf(item.getAge());
            arr[3] = item.getMajor();
            arr[4] = item.getGrade();
            arr[5] = item.getloveSubj();
            // 添加数据到表格
            tableModel.addRow(arr);
        }
    }

    public void search(int sid) {
        Student student = service.selectBySid(sid);
        if (student != null) {
            DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
            tableModel.setRowCount(0);// 清除原有行

            String[] arr = new String[6];

            arr[0] = student.getSid() + "";
            arr[1] = student.getName();
            arr[2] = String.valueOf(student.getAge());
            arr[3] = student.getMajor();
            arr[4] = student.getGrade();
            arr[5] = student.getloveSubj();
            // 添加数据到表格
            tableModel.addRow(arr);
        } else {
            JOptionPane.showMessageDialog(contentPane, "不存在该学生", "系统提示", JOptionPane.WARNING_MESSAGE);
        }
    }

}

(4)UpdateView(修改信息界面)

package GUITest;

import pojo.Student;
import service.studentService;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

/**
 * @author观止
 */
public class UpdateView extends JFrame {

    private JPanel contentPane;
    private JTextField sidText;
    private JTextField nameText;
    private JTextField ageText;
    private JTextField majorText;
    private JTextField gradeText;
    private JTextField loveSubjText;

    private studentService service = new studentService();

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            try {
                UpdateView frame = new UpdateView(1);
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * Create the frame.
     */
    public UpdateView(final int sid) {
        setTitle("学生编辑");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setBounds(100, 100, 443, 450);
        setLocationRelativeTo(null);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JLabel lblNewLabel = new JLabel("学号:");
        lblNewLabel.setBounds(112, 50, 43, 15);
        contentPane.add(lblNewLabel);

        sidText = new JTextField();
        sidText.setBounds(151, 47, 160, 21);
        contentPane.add(sidText);
        sidText.setColumns(10);

        JLabel lblNewLabel_1 = new JLabel("姓名:");
        lblNewLabel_1.setBounds(112, 93, 43, 15);
        contentPane.add(lblNewLabel_1);

        nameText = new JTextField();
        nameText.setBounds(151, 90, 160, 21);
        contentPane.add(nameText);
        nameText.setColumns(10);

        JLabel lblNewLabel_2 = new JLabel("年龄:");
        lblNewLabel_2.setBounds(112, 134, 43, 15);
        contentPane.add(lblNewLabel_2);

        ageText = new JTextField();
        ageText.setBounds(151, 130, 160, 21);
        contentPane.add(ageText);
        ageText.setColumns(10);

        JLabel lblNewLabel_3 = new JLabel("专业:");
        lblNewLabel_3.setBounds(112, 177, 43, 15);
        contentPane.add(lblNewLabel_3);

        majorText = new JTextField();
        majorText.setBounds(151, 177, 160, 21);
        contentPane.add(majorText);
        majorText.setColumns(10);

        JLabel lblNewLabel_4 = new JLabel("班级:");
        lblNewLabel_4.setBounds(111, 220, 43, 15);
        contentPane.add(lblNewLabel_4);

        gradeText = new JTextField();
        gradeText.setBounds(151, 220, 160, 21);
        contentPane.add(gradeText);
        gradeText.setColumns(10);

        JLabel lblNewLabel_5 = new JLabel("偏爱学科:");
        lblNewLabel_5.setBounds(90, 263, 70, 15);
        contentPane.add(lblNewLabel_5);

        loveSubjText = new JTextField();
        loveSubjText.setBounds(151, 263, 160, 21);
        contentPane.add(loveSubjText);
        loveSubjText.setColumns(10);

        //保存
        JButton saveBtn = new JButton("保存");
        saveBtn.addActionListener(e -> {

            String sid1 = sidText.getText();
            String name = nameText.getText();
            String age = ageText.getText();
            String major = majorText.getText();
            String grade = gradeText.getText();
            String loveSubj = loveSubjText.getText();
            if (sid1 == null || "".equals(sid1)) {
                JOptionPane.showMessageDialog(contentPane, "请输入学号", "系统提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            if (name == null || "".equals(name)) {
                JOptionPane.showMessageDialog(contentPane, "请输入姓名", "系统提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            if (age == null || "".equals(age)) {
                JOptionPane.showMessageDialog(contentPane, "请输入年龄", "系统提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            if (major == null || "".equals(major)) {
                JOptionPane.showMessageDialog(contentPane, "请输入专业", "系统提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            if (grade == null || "".equals(grade)) {
                JOptionPane.showMessageDialog(contentPane, "请输入年纪", "系统提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            if (loveSubj == null || "".equals(loveSubj)) {
                JOptionPane.showMessageDialog(contentPane, "请输入偏爱学科", "系统提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            Student student = new Student();
            student.setSid(Integer.parseInt(sid1));
            student.setName(name);
            student.setAge(Integer.parseInt(age));
            student.setMajor(major);
            student.setGrade(grade);
            student.setloveSubj(loveSubj);
            service.update(student);
            dispose();
            JOptionPane.showMessageDialog(contentPane, "修改成功,点击查询刷新数据!");

        });
        saveBtn.setBounds(151, 300, 74, 23);
        contentPane.add(saveBtn);

        //取消
        JButton cancelBtn = new JButton("取消");
        cancelBtn.addActionListener(e -> dispose());
        cancelBtn.setBounds(237, 300, 74, 23);
        contentPane.add(cancelBtn);

        //数据回显
        Student student = service.selectBySid(sid);
        sidText.setText(String.valueOf(student.getSid()));
        nameText.setText(student.getName());
        ageText.setText(String.valueOf(student.getAge()));
        majorText.setText(student.getMajor());
        gradeText.setText(student.getGrade());
        loveSubjText.setText(student.getloveSubj());
    }

}

(5)AddView(添加学生界面)

package GUITest;

import pojo.Student;
import service.studentService;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

/**
 * @author 观止
 */
public class AddView extends JFrame {

    private JPanel contentPane;
    private JTextField sidText;
    private JTextField nameText;
    private JTextField ageText;
    private JTextField majorText;
    private JTextField gradeText;
    private JTextField loveSubjText;

    private studentService service = new studentService();

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            try {
                AddView frame = new AddView();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * Create the frame.
     */
    public AddView() {
        setTitle("学生添加");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setBounds(100, 100, 443, 450);
        setLocationRelativeTo(null);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JLabel lblNewLabel = new JLabel("学号:");
        lblNewLabel.setBounds(112, 50, 43, 15);
        contentPane.add(lblNewLabel);

        sidText = new JTextField();
        sidText.setBounds(151, 47, 160, 21);
        contentPane.add(sidText);
        sidText.setColumns(10);

        JLabel lblNewLabel_1 = new JLabel("姓名:");
        lblNewLabel_1.setBounds(112, 93, 43, 15);
        contentPane.add(lblNewLabel_1);

        nameText = new JTextField();
        nameText.setBounds(151, 90, 160, 21);
        contentPane.add(nameText);
        nameText.setColumns(10);

        JLabel lblNewLabel_2 = new JLabel("年龄:");
        lblNewLabel_2.setBounds(112, 134, 43, 15);
        contentPane.add(lblNewLabel_2);

        ageText = new JTextField();
        ageText.setBounds(151, 130, 160, 21);
        contentPane.add(ageText);
        ageText.setColumns(10);

        JLabel lblNewLabel_3 = new JLabel("专业:");
        lblNewLabel_3.setBounds(112, 177, 43, 15);
        contentPane.add(lblNewLabel_3);

        majorText = new JTextField();
        majorText.setBounds(151, 177, 160, 21);
        contentPane.add(majorText);
        majorText.setColumns(10);

        JLabel lblNewLabel_4 = new JLabel("班级:");
        lblNewLabel_4.setBounds(111, 220, 43, 15);
        contentPane.add(lblNewLabel_4);

        gradeText = new JTextField();
        gradeText.setBounds(151, 220, 160, 21);
        contentPane.add(gradeText);
        gradeText.setColumns(10);

        JLabel lblNewLabel_5 = new JLabel("偏爱学科:");
        lblNewLabel_5.setBounds(90, 263, 70, 15);
        contentPane.add(lblNewLabel_5);

        loveSubjText = new JTextField();
        loveSubjText.setBounds(151, 263, 160, 21);
        contentPane.add(loveSubjText);
        loveSubjText.setColumns(10);

        //保存
        JButton saveBtn = new JButton("保存");
        saveBtn.addActionListener(e -> {

            String sid = sidText.getText();
            String name = nameText.getText();
            String age = ageText.getText();
            String major = majorText.getText();
            String grade = gradeText.getText();
            String loveSubj = loveSubjText.getText();
            if (sid == null || "".equals(sid)) {
                JOptionPane.showMessageDialog(contentPane, "请输入学号", "系统提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            if (name == null || "".equals(name)) {
                JOptionPane.showMessageDialog(contentPane, "请输入姓名", "系统提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            if (age == null || "".equals(age)) {
                JOptionPane.showMessageDialog(contentPane, "请输入年龄", "系统提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            if (major == null || "".equals(major)) {
                JOptionPane.showMessageDialog(contentPane, "请输入专业", "系统提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            if (grade == null || "".equals(grade)) {
                JOptionPane.showMessageDialog(contentPane, "请输入年纪", "系统提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            if (loveSubj == null || "".equals(loveSubj)) {
                JOptionPane.showMessageDialog(contentPane, "请输入偏爱学科", "系统提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            Student student = new Student();
            student.setSid(Integer.parseInt(sid));
            student.setName(name);
            student.setAge(Integer.parseInt(age));
            student.setMajor(major);
            student.setGrade(grade);
            student.setloveSubj(loveSubj);
            try {
                service.add(student);
                dispose();
                JOptionPane.showMessageDialog(contentPane, "添加成功,点击查询可刷新!");

            }catch (Exception error){
                JOptionPane.showMessageDialog(contentPane, "该学号已存在", "系统提示", JOptionPane.WARNING_MESSAGE);
            }

        });
        saveBtn.setBounds(151, 300, 74, 23);
        contentPane.add(saveBtn);

        //取消
        JButton cancelBtn = new JButton("取消");
        cancelBtn.addActionListener(e -> dispose());
        cancelBtn.setBounds(237, 300, 74, 23);
        contentPane.add(cancelBtn);
    }

}

六.工具类

package util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
/**
 * @author 观止
 */
public class SqlSessionFactoryUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        //静态代码块会随着类的加载自动执行,且只执行一次

        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
             sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

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

    }

    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }
}

七.配置文件

(1)pom文件


    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

    <dependencies>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.23</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>16</source>
                    <target>16</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

(2)mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--起别名-->
    <typeAliases>
        <package name="pojo"/>
    </typeAliases>

<!--url,username,password改成自己的-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///studentmessage?useSSL=false&amp;useServerPrepStmts=true"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--扫描mapper-->
        <package name="mapper"/>
    </mappers>
</configuration>

(3)StudentMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mapper.StudentMapper">

    <insert id="add">
        insert into studentall
        values (#{sid}, #{name}, #{age}, #{major}, #{grade}, #{loveSubj})
    </insert>
    <update id="update">
        UPDATE studentall
        SET name=#{name},
            age=#{age},
            major=#{major},
            grade=#{grade},
            loveSubj=#{loveSubj}
        WHERE sid = #{sid}
    </update>

    <delete id="delete">
        delete
        from studentall
        where sid = #{sid}
    </delete>

    <select id="selectAll" resultType="pojo.Student">
        select *
        from studentAll
    </select>
    <select id="selectBySid" resultType="pojo.Student">
        select *
        from studentAll
        where sid = #{sid}
    </select>

</mapper>

(4)UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mapper.UserMapper">

<!--用的注解开发sql语句都在接口里-->

</mapper>

四.待优化处及gitee仓库地址

1.由于不熟悉图形界面的开发,图形界面开发的比较简陋,各种按钮及标签的坐标都是一点一点移动对齐的,页面展示的功能也比较简单。

2.数据创建学生信息表时直接将学号sid当成主键为int型,结果后期调试时发现输入超过10位的学号程序便会抛出异常,由于需要改的地方太多了便没有修改,我觉得此处多设置一个主键id,然后将sid设置为String型比较好。

git仓库地址,感谢Star:studentManageSystem: 学生信息管理系统,swing+mybatis

git clone https://gitee.com/fspStudy/student-manage-system.git
标签: java idea

本文转载自: https://blog.csdn.net/m0_66570338/article/details/124746800
版权归原作者 观止study 所有, 如有侵权,请联系我们删除。

“(附完整代码)Java学生信息管理系统结合图形界面展示”的评论:

还没有评论