1.项目目录介绍
entity包为Javabean类,里面存放了Student表的信息
Student.java
package com.a_studentsys.entity;
/**
* @author Anonymous 2020/3/25 10:59
*/
public class Student {
private Integer id;
private String name;
private Integer age;
private Boolean gender;
private Float score;
private String address;
public Student() {
}
public Student(String name, Integer age, Boolean gender, Float score, String address) {
this.name = name;
this.age = age;
this.gender = gender;
this.score = score;
this.address = address;
}
public Student(Integer id, String name, Integer age, Boolean gender, Float score, String address) {
this.id = id;
this.name = name;
this.age = age;
this.gender = gender;
this.score = score;
this.address = address;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Boolean getGender() {
return gender;
}
public void setGender(Boolean gender) {
this.gender = gender;
}
public Float getScore() {
return score;
}
public void setScore(Float score) {
this.score = score;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", gender=" + gender +
", score=" + score +
", address='" + address + '\'' +
'}';
}
}
controller包为控制层,
StudentController.java
package controller;
import com.a_studentsys.entity.Student;
import service.StudentService;
import service.impl.StudentServiceImpl;
import view.StudentView;
import view.impl.StudentViewImpl;
import java.math.BigDecimal;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class StudentController {
/*
StudentServiceImpl层实现类对象,提供服务
*/
private StudentService studentService = new StudentServiceImpl();
/*
studentView 界面层实现类对象,童工界面展示
*/
private StudentView studentView = new StudentViewImpl();
private Scanner scanner =new Scanner(System.in);
public void addStudent(){
studentView.inputStudentName();
String name =scanner.next();
studentView.inputStudentAge();
int age = scanner.nextInt();
studentView.inputStudentGender();
boolean gender = scanner.nextBoolean();
studentView.inputStudentScore();
float score = scanner.nextFloat();
studentView.inputStudentAddress();
String address = scanner.next();
Student student = new Student(name, age, gender, score, address);
studentService.addStudent(student);
}
public void deleteStudent(){
studentView.inputStudentId();
int id =scanner.nextInt();
Student student = studentService.findStudentById(id);
if (null == student){
studentView.notFound();
return;
}
studentView.showStudentInfo(student);
studentView.deleteConfirm();
if (scanner.nextBoolean()){
studentService.deleteStudentById(id);
}else {
studentView.operationCancel();
}
}
public void modifyStudentById(){
studentView.inputStudentId();
int id= scanner.nextInt();
Student student = studentService.findStudentById(id);
if (null == student){
studentView.notFound();
return;
}
int choose =0;
boolean flag = false;
while (true){
studentView.modifyStudentMenu(student);
choose= scanner.nextInt();
switch (choose){
case 1:
studentView.inputStudentName();
String name = scanner.next();
student.setName(name);
break;
case 2:
studentView.inputStudentAge();
int age = scanner.nextInt();
student.setAge(age);
break;
case 3:
studentView.inputStudentGender();
boolean gender = scanner.nextBoolean();
student.setGender(gender);
break;
case 4:
studentView.inputStudentScore();
float score = scanner.nextFloat();
student.setScore(score);
break;
case 5:
studentView.inputStudentAddress();
String address = scanner.next();
student.setAddress(address);
break;
case 6:
flag = true;
break;
default:
break;
}
if (flag){
studentService.updateStudent(student);
break;
}
}
}
public void findStudentId(){
studentView.inputStudentId();
int id = scanner.nextInt();
Student student = studentService.findStudentById(id);
if (student !=null){
studentView.showStudentInfo(student);
}else {
studentView.notFound();
}
}
public void findAllStudent(){
List<Student> list = studentService.findAllStudents();
if (list != null){
studentView.showStudentList(list);
}else {
studentView.notFound();
}
}
/**
* 按照条件排序
*/
public void sort() {
studentView.sortOperationChoose();
int choose = scanner.nextInt();
List<Student> list = null;
switch (choose) {
case 1:
// 年龄升序
list = studentService.sortUsingCompare(Comparator.comparingInt(Student::getAge));
break;
case 2:
// 成绩降序
list = studentService.sortUsingCompare((stu1, stu2) -> {
BigDecimal bigDecimal1 = new BigDecimal(stu1.getScore() + "");
BigDecimal bigDecimal2 = new BigDecimal(stu2.getScore() + "");
return bigDecimal2.compareTo(bigDecimal1);
});
break;
default:
studentView.chooseError();
break;
}
if (list != null) {
studentView.showStudentList(list);
} else {
studentView.notFound();
}
}
public void mainMenu(){
studentView.mainMenu();
}
public void chooseError(){
studentView.chooseError();
}
}
dao包是dao层
StudentDao.java
package dao;
import com.a_studentsys.entity.Student;
import java.util.List;
public interface StudentDao {
/*
增
删
改
查:
1.查单个
2.查所有
*/
/**
* 添加学生方法要求,参数为Student类对象,返回值为int类型,成功返回1 失败返回0
* @param student Student类对象
* @return 添加成功返回1 失败返回0
*/
int addStudent(Student student);
/**
* 根据指定的id删除对应的学生
* @param id 指定的id
* @return 删除成功返回1 失败返回0
*/
int deleteStudent(int id);
/**
* 修改学生信息,传入的参数是个Student类对象
* @param student Student类对象
* @return 更新成功返回1 失败返回0
*/
int updateStudent(Student student);
/**
* 查询指定id的学生
* 没有找到返回null
* @param id
* @return 查询陈宫返回Student类对象,失败返回null
*/
Student findStudentById(int id);
/**
* 查询当前数据库中所有学生信息
* @return 成功返回List集合 如果没有数据返回null
*/
List<Student> findAllStudent();
}
StudentDaoImpl.java
package dao.impl;
import com.a_studentsys.entity.Student;
import dao.StudentDao;
import util.BaseDao;
import java.util.List;
/**
* 这里需要继承BaseDao对于数据库操作的Update Query方法
* 同时遵从StudentDao接口,完成方法实现,当前类使用一个符合StudentDao规范的实现类
*/
public class StudentDaoImpl extends BaseDao implements StudentDao {
@Override
public int addStudent(Student student) {
String sql = "insert into test.student(name, age, gender, score, address) value (?,?,?,?,?)";
Object[] parameters = {student.getName(),student.getAge(),student.getGender(),student.getScore(),student.getAddress()};
return super.update(sql,parameters);
}
@Override
public int deleteStudent(int id) {
String sql = "delete from test.student where id= "+id;
return super.update(sql,null);
}
@Override
public int updateStudent(Student student) {
String sql = "update test.student set name=?,age=?,gender=?,score=?,address=? where id=?";
Object[] parameters = {student.getName(),student.getAge(),student.getGender(),student.getScore(),student.getAddress(),student.getId()};
return super.update(sql,parameters);
}
@Override
public Student findStudentById(int id) {
String sql="select * from test.student where id="+id;
Student student = super.queryBean(sql, null, Student.class);
return student;
}
@Override
public List<Student> findAllStudent() {
String sql="select * from test.student";
return super.queryBeanList(sql, null, Student.class);
}
}
main包里包含main方法
mainProject.java
package main;
import controller.StudentController;
import java.util.Scanner;
public class mainProject {
/*
View界面
*/
private static Scanner scanner = new Scanner(System.in);
private static StudentController studentController = new StudentController();
public static void main(String[] args) {
int choose = 0;
boolean flag = false;
while (flag){
studentController.mainMenu();
choose = scanner.nextInt();
switch (choose){
case 1:
studentController.addStudent();
break;
case 2:
studentController.deleteStudent();
break;
case 3:
studentController.modifyStudentById();
break;
case 4:
studentController.findStudentId();
break;
case 5:
studentController.findAllStudent();
break;
case 6:
studentController.sort();
break;
case 7:
flag=flag;
break;
default:
studentController.chooseError();
break;
}
}
}
}
service包是服务层,包括了服务以及服务的实现类
StudentService.java
package service;
import com.a_studentsys.entity.Student;
import java.util.Comparator;
import java.util.List;
public interface StudentService {
/*
增删改查排序
*/
/**
* Service层规定的添加学生方法,返回值类型是boolean
*
* @param student Student类对象
* @return 添加成功返回true,失败返回false
*/
boolean addStudent(Student student);
/**
* 删除指定ID学生
*
* @param id 指定学生的ID
* @return 删除成功返回true,失败返回false
*/
boolean deleteStudentById(Integer id);
/**
* 更新学生信息
*
* @param student 需要更新信息的一个Student类对象
* @return 更新成功返回true,失败返回false
*/
boolean updateStudent(Student student);
/**
* 查询指定ID的学生
*
* @param id 指定的学生的ID号
* @return Student类对象,没有找到返回null
*/
Student findStudentById(Integer id);
/**
* 查询所有的学生类对象,存储于List集合中
*
* @return List集合,没有数据返回null
*/
List<Student> findAllStudents();
/**
* 按照提供的方法,排序学生信息保存到List集合中
*
* @param comparator Comparator函数式接口要求规范
* @return List集合,排序之后的学生数据,没有数据返回null
*/
List<Student> sortUsingCompare(Comparator<Student> comparator);
}
StudentServiceImpl.java
package service.impl;
import com.a_studentsys.entity.Student;
import dao.StudentDao;
import dao.impl.StudentDaoImpl;
import service.StudentService;
import java.util.Comparator;
import java.util.List;
public class StudentServiceImpl implements StudentService {
/*
准备一个StudentDao层的实现类对象,帮助操作数据库
*/
StudentDao studentDao = new StudentDaoImpl();
@Override
public boolean addStudent(Student student) {
return studentDao.addStudent(student) !=0;
}
@Override
public boolean deleteStudentById(Integer id) {
return studentDao.deleteStudent(id) !=0;
}
@Override
public boolean updateStudent(Student student) {
return studentDao.updateStudent(student) !=0;
}
@Override
public Student findStudentById(Integer id) {
return studentDao.findStudentById(id);
}
@Override
public List<Student> findAllStudents() {
return studentDao.findAllStudent();
}
@Override
public List<Student> sortUsingCompare(Comparator<Student> comparator) {
List<Student> list = studentDao.findAllStudent();
if (list != null){
list.sort(comparator);
}
return list;
}
}
util包里是工具包,封装了数据库的增删改查方法
BaseDao.java
package util;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
/**
* BaseDao 数据库操作基类
* 1. 通用更新
* 2. 通用查询
*
* @author Anonymous 2020/3/24 16:01
*/
public class BaseDao {
/**
* 通用的更新方法,需要参数是SQL语句和对应当前SQL语句的Object类型参数数组
*
* @param sql String类型的SQL语句,需要执行的方法
* @param parameters 对应当前SQL语句的参数列表。Object类型数组
* @return SQL语句执行数据库受到影响的行数
*/
public int update(String sql, Object[] parameters) {
// DbUtils核心类,QueryRunner
QueryRunner runner = new QueryRunner();
Connection connection = JdbcUtil.getConnection();
int affectedRows = 0;
try {
affectedRows = runner.update(connection, sql, parameters);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.close(connection);
}
return affectedRows;
}
/**
* 通用的查询方法,查询cls指定数据类型,单一对象
*
* @param sql Select SQL语句
* @param parameters 对应当前SQL语句的参数
* @param cls 指定数据类型,同时提供Class对象,便于里用反射操作,约束泛型类型
* @param <T> 泛型占位符
* @return 单一指定类型对象,没有找到返回null
*/
public <T> T queryBean(String sql, Object[] parameters, Class<T> cls) {
// DbUtils核心类,QueryRunner
QueryRunner runner = new QueryRunner();
Connection connection = JdbcUtil.getConnection();
T t = null;
try {
t = runner.query(connection, sql, new BeanHandler<>(cls), parameters);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.close(connection);
}
return t;
}
/**
* 通用的查询方法,查询cls指定数据类型,包含指定对象的List集合
*
* @param sql Select SQL语句
* @param parameters 对应当前SQL语句的参数
* @param cls 指定数据类型,同时提供Class对象,便于里用反射操作,约束泛型类型
* @param <T> 泛型占位符
* @return 返回包含指定对象的List集合,没有数据返回null
*/
public <T> List<T> queryBeanList(String sql, Object[] parameters, Class<T> cls) {
// DbUtils核心类,QueryRunner
QueryRunner runner = new QueryRunner();
Connection connection = JdbcUtil.getConnection();
List<T> list = null;
try {
list = runner.query(connection, sql, new BeanListHandler<>(cls), parameters);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.close(connection);
}
return list;
}
/**
* 通用查询方法,返回值是对应字段数据的Object类型数组,并且存储于List集合
*
* @param sql Select查询SQL语句
* @param parameters 对应当前SQL语句的参数
* @return 包含数据行数据的List<Object[]> 如果没有查询到数据,返回null
*/
public List<Object[]> queryArrayList(String sql, Object[] parameters) {
QueryRunner runner = new QueryRunner();
Connection connection = JdbcUtil.getConnection();
List<Object[]> list = null;
try {
list = runner.query(connection, sql, new ArrayListHandler(), parameters);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.close(connection);
}
return list;
}
}
JdbcUtil.java
package util;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
/**
* JDBC工具类,负责数据库连接对象和数据库资源关闭
*
* @author Anonymous 2020/3/24 10:08
*/
public class JdbcUtil {
// 静态成员变量,保存一些必要的数据
private static String url = null;
private static String user = null;
private static String password = null;
// 利用static修饰的静态代码块完成文件字段自动读取和驱动自动加载过分
static {
try {
// Properties实现类,里面的数据保存形式都是键值对形式
Properties properties = new Properties();
// 使用字节输入流,加载对应db.properties,数据保存到Properties对象中
properties.load(new FileInputStream("./src/db.properties"));
// 从Properties读取对应的数据
String driverClass = properties.getProperty("driverClass");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
// 完整驱动加载
Class.forName(driverClass);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 返回数据库连接对象,连接失败返回null
*
* @return java.sql.Connection 数据库连接对象
*/
public static Connection getConnection() {
Connection connection = null;
try {
// 通过DriverManager驱动管理类,使用必要参数获取数据库连接
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
/*
以下三个方法实际上都是执行同一个方法,使用这种方式
1. 简化代码结构
2. 规范化所有的操作
*/
/**
* 处理数据库操作对应的资源问题
*
* @param connection java.sql.Connection 数据库连接对象
*/
public static void close(Connection connection) {
close(connection, null, null);
}
/**
* 处理数据库操作对应的资源问题
*
* @param connection java.sql.Connection 数据库连接对象
* @param statement java.sql.Statement 数据库SQL语句搬运工对象
*/
public static void close(Connection connection, Statement statement) {
close(connection, statement, null);
}
/**
* 处理数据库操作对应的资源问题
*
* @param connection java.sql.Connection 数据库连接对象
* @param statement java.sql.Statement 数据库SQL语句搬运工对象
* @param resultSet java.sql.ResultSet 数据库查询结果集对象
*/
public static void close(Connection connection, Statement statement, ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
view为视图层
StudentView.java
package view;
import com.a_studentsys.entity.Student;
import java.util.List;
public interface StudentView {
/**
* 提示用户输入ID
*/
void inputStudentId();
/**
* 提示用户输入醒目
*/
void inputStudentName();
/**
* 提示用户输入年龄
*/
void inputStudentAge();
/**
* 提示用户输入性别
*/
void inputStudentGender();
/**
* 提示用户输入成绩
*/
void inputStudentScore();
/**
* 提示用户输入住址
*/
void inputStudentAddress();
/**
* 展示一个学生信息
*
* @param student Student类对象
*/
void showStudentInfo(Student student);
/**
* 删除确认提示
*/
void deleteConfirm();
/**
* 操作取消
*/
void operationCancel();
/**
* Not Found!!! ==> 404
*/
void notFound();
/**
* 展示List集合的中的Student类对象
* @param students List集合
*/
void showStudentList(List<Student> students);
/**
* 排序选择提示
*/
void sortOperationChoose();
/**
* 修改学生菜单
* @param student Student
*/
void modifyStudentMenu(Student student);
/**
* 选择错误提示
*/
void chooseError();
/**
* 主菜单,主界面
*/
void mainMenu();
}
StudentViewImpl.java
package view.impl;
import com.a_studentsys.entity.Student;
import view.StudentView;
import java.util.List;
/**
* @author Anonymous 2020/3/25 11:36
*/
public class StudentViewImpl implements StudentView {
@Override
public void inputStudentId() {
System.out.println("请输入学生的ID号:");
}
@Override
public void inputStudentName() {
System.out.println("请输入学生的姓名:");
}
@Override
public void inputStudentAge() {
System.out.println("请输入学生的年龄:");
}
@Override
public void inputStudentGender() {
System.out.println("请输入学生的性别 true => 男 false => 女:");
}
@Override
public void inputStudentScore() {
System.out.println("请输入学生的成绩:");
}
@Override
public void inputStudentAddress() {
System.out.println("请输入学生的地址:");
}
@Override
public void showStudentInfo(Student student) {
System.out.println(student);
}
@Override
public void deleteConfirm() {
System.out.println("确定删除吗? true or false");
}
@Override
public void operationCancel() {
System.out.println("操作取消");
}
@Override
public void notFound() {
System.out.println("查无此人");
}
@Override
public void showStudentList(List<Student> students) {
for (Student student : students) {
System.out.println(student);
}
}
@Override
public void sortOperationChoose() {
System.out.println("1. 年龄升序");
System.out.println("2. 成绩降序");
}
@Override
public void modifyStudentMenu(Student student) {
System.out.println("ID:" + student.getId() + " Name:" + student.getName());
System.out.println("Age:" + student.getAge() + " Gender:" + (student.getGender() ? "男" : "女"));
System.out.println("Score:" + student.getScore() + " Address:" + student.getAddress());
System.out.println("1. 修改学生的名字");
System.out.println("2. 修改学生的年龄");
System.out.println("3. 修改学生的性别");
System.out.println("4. 修改学生的成绩");
System.out.println("5. 修改学生的地址");
System.out.println("6. 退出保存");
}
@Override
public void chooseError() {
System.out.println("选择错误!!!");
}
@Override
public void mainMenu() {
System.out.println("1. 添加学生");
System.out.println("2. 删除指定ID学生");
System.out.println("3. 修改指定ID学生");
System.out.println("4. 查询指定ID学生");
System.out.println("5. 查询所有学生");
System.out.println("6. 按照条件排序学生信息");
System.out.println("7. 退出");
}
}
最后的连接驱动db.properties
# 当前JDBC连接所需的驱动
driverClass=com.mysql.jdbc.Driver
# 数据库连接符合JDBC规范的url
url=jdbc:mysql://localhost:3306/test?useSSL=true
# 用户名
user=root
# 密码
password=root
结果