Java项目:员工管理系统(用数据库进行存储数据)

Employee(模板类):
package com.employee.mysql; import java.io.Serializable; /** * 员工类 */ public class Employee implements Serializable { private String name;// 姓名 private String age;// 年龄 private String sex;// 性别 private Integer id;// 工号 public Employee() { } public Employee(String name, String age, String sex, int id) { this.setName(name); this.setAge(age); this.setSex(sex); this.setId(id); } public Employee(String name, String age, String sex) { this.setName(name); this.setAge(age); this.setSex(sex); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Override public String toString() { return "Employees [name=" + name + ", age=" + age + ", sex=" + sex + ", id=" + id + "]"; } }
SystemView(系统视图类):
package com.employee.mysql; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import com.liuguangfa.employee.list.Employees; public class SystemView { Scanner scanner = new Scanner(System.in); // 用于接收dao的实现类 EmployeeDAOimpl employeeDAOimpl = null; // 通过构造函数去传递进来 public SystemView(EmployeeDAOimpl employeeDAOimpl) { this.employeeDAOimpl = employeeDAOimpl; } public void start() { System.out.println("欢迎来到员工管理系统"); String ai = "10"; do { if (ai.equals("1")) { addEmp(); ai = "10"; } if (ai.equals("2")) { deleteEmp(); ai = "10"; } if (ai.equals("3")) { modify(); ai = "10"; } if (ai.equals("4")) { query(); ai = "10"; } if (ai.equals("5")) { // exitApp(); break; } else { System.out.println("请输入你要进行的操作1.增加员工2.开除员工3.修改员工信息4.查询员工5.退出系统"); ai = scanner.next(); } } while (true); } /** * 添加员工 */ public void addEmp() { List<Employee> emps = new ArrayList<>(); boolean bool = false; do { System.out.println("请输入员工的姓名"); String name = scanner.next(); System.out.println("请输入员工的年龄"); String age = scanner.next(); System.out.println("请输入员工的性别"); String sex = scanner.next(); Employee emp = new Employee(name, age, sex); emps.add(emp); System.out.println("是否继续创建新的员工信息y/n"); String isYesAndNo = scanner.next(); if (isYesAndNo.toLowerCase().equals("y")) { bool = true; } else { bool = false; } } while (bool); employeeDAOimpl.addEmployee(emps); } /** * 删除员工信息 */ public void deleteEmp() { boolean isDelete = false; do { System.out.println("请选择开除员工的方式1.按姓名2.按照id"); int count = scanner.nextInt(); if (count == 1) { System.out.println("请输入你开除员工的姓名"); String name = scanner.next(); boolean bool = employeeDAOimpl.deleteEmployee(name); if (bool) { System.out.println("您开除员工成功"); } else { System.out.println("你开除员工失败,请检查后重新输入"); } } else if (count == 2) { System.out.println("请输入你要开除员工的id"); int id = scanner.nextInt(); boolean bool = employeeDAOimpl.deleteEmployee(id); if (bool) { System.out.println("您开除员工成功"); } else { System.out.println("你开除员工失败,请检查后重新输入"); } } System.out.println("是否继续开除的员工y/n"); String isYesAndNo = scanner.next(); if (isYesAndNo.toLowerCase().equals("y")) { isDelete = true; } else { isDelete = false; } } while (isDelete); } /** * 修改员工 */ public void modify() { boolean e = false; do { System.out.println("请输入你要修改员工的id"); int id = scanner.nextInt(); System.out.println("请选择你要修改的选项1.姓名2.年龄3.性别"); int isModify = scanner.nextInt(); if (isModify == 1) { System.out.println("请输入你要修改成为什么名字?"); String name = scanner.next(); employeeDAOimpl.replaceByName(name, id); System.out.println("您修改成功"); } else if (isModify == 2) { System.out.println("请输入你要修改成为多少年龄?"); String age = scanner.next(); employeeDAOimpl.replaceByAge(age, id); System.out.println("您修改成功"); } else if (isModify == 3) { System.out.println("请输入你要修改成为什么性别?仅限男女"); String sex = scanner.next(); if (sex.equals("男")) { employeeDAOimpl.replaceBysex(sex, id); } else if (sex.equals("女")) { employeeDAOimpl.replaceBysex(sex, id); } else { System.out.println("您输入错误请重新输入"); } System.out.println("您修改成功"); } System.out.println("是否继续修改的员工信息y/n"); String isYesAndNo = scanner.next(); if (isYesAndNo.toLowerCase().equals("y")) { e = true; } else { e = false; } } while (e); } /** * 查询员工信息 */ public void query() { boolean bool = false; do { System.out.println("请选择查询方式1.全部查询2.按照姓名查询3.按照id查询"); int count = scanner.nextInt(); List<Employee> emps = new ArrayList<>(); if (count == 1) { emps = employeeDAOimpl.findAll(); for (int i = 0; i < emps.size(); i++) { Employee emp = emps.get(i); System.out.println("第" + (i + 1) + " 名员工是" + emp.toString()); } } else if (count == 2) { System.out.println("请输入你查询的姓名"); String name = scanner.next(); emps = employeeDAOimpl.findByName(name); if (emps.size() == 0) { System.out.println("您输入有误,请重新输入"); } for (int i = 0; i < emps.size(); i++) { Employee emp = emps.get(i); System.out.println("第" + (i + 1) + " 名员工是" + emp.toString()); } } else if (count == 3) { System.out.println("请输入你查询的id,仅可输入数字序号"); Integer id = scanner.nextInt(); emps = employeeDAOimpl.finById(id); if (emps.size() == 0) { System.out.println("您输入有误,请重新输入"); } for (int i = 0; i < emps.size(); i++) { Employee emp = emps.get(i); System.out.println("第" + (i + 1) + " 名员工是" + emp.toString()); } } else { System.out.println("您输入有误,请重新输入"); } System.out.println("是否继续查询的员工信息y/n"); String isYesAndNo = scanner.next(); if (isYesAndNo.toLowerCase().equals("y")) { bool = true; } else { bool = false; } } while (bool); } }
Global(公共变量):
package com.employee.mysql; import java.sql.Connection; /** * 全局的变量或方法 */ public class Global { public static final String url = "jdbc:mysql://localhost:3306/employee?charaterEncoding=UTF-8&useSSL=false&autoReconnect=true&serverTimeZone=Asia/Shanghai"; public static final String username = "root"; public static final String password = "123456"; /** * 获取数据库连接 * * @return */ public static Connection getConnection() { return JdbcUtils.getConnection(url, username, password); } }
Application(main方法类,系统入口):
package com.employee.mysql; public class Application { public static void main(String[] args) { //创建DAOimpl EmployeeDAOimpl employeeDAOimpl = new EmployeeDAOimpl(); //创建员工视图 SystemView systemView = new SystemView(employeeDAOimpl); //调用试图开始 systemView.start(); } }
JdbcUtils(数据库读取的工具类):
package com.employee.mysql; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.lgf.shejimoshi.Logger; public class JdbcUtils { private final static String DRIVER = "com.mysql.cj.jdbc.Driver"; //创建日志管理器 private static Logger LOGGER = new SetLogger(); /** * 查询 */ public static <T> List<T> query(boolean antoClose, Connection conn, String sql, ResultSetHandler<List<T>> handler, Object... args) { try { // 创建数据库载体 PreparedStatement ps = conn.prepareStatement(sql); for (int i = 0; i < args.length; i++) { Object arg = args[i]; ps.setObject(i + 1, arg); } // 进行数据库查询,返回查询结果 ResultSet rs = ps.executeQuery(); return handler.handle(rs); } catch (SQLException e) { LOGGER.error("创建数据库载体失败"); //e.printStackTrace(); } finally { if (antoClose) { close(conn); } } return null; } public <T> List<T> query(Connection conn, ResultSetHandler<List<T>> handler, String sql, Object... args) { return query(false, conn, sql, handler, args); } /** * 结果集转换成T 类型的接口 * * @author liugu * */ public static interface ResultSetHandler<T> { public T handle(ResultSet rs); } /** * 结果集转换器的实现类 */ public static class ResuleSetHenderImpl<T> implements ResultSetHandler<List<T>> { // 创建map集合,用于存放属性描述符、属性名称 private final Map<String, PropertyDescriptor> bdsMap = new HashMap<>(); // 创建构造函数,需要传进来一个class的值 private final Class<T> clazz; public ResuleSetHenderImpl(Class<T> clazz) { this.clazz = clazz; try { // 通过class获取类的元数据 BeanInfo bi = Introspector.getBeanInfo(clazz); // 通过类的元数据获取属性描述符数组 PropertyDescriptor[] bds = bi.getPropertyDescriptors(); // 把属性描述符和属性名称存在map集合中 for (PropertyDescriptor bd : bds) { bdsMap.put(bd.getName(), bd); } } catch (IntrospectionException e) { // e.printStackTrace(); LOGGER.error("结果集转换失败"); } } @Override public List<T> handle(ResultSet rs) { List<T> results = new ArrayList<>(); try { // 创建结果集列名存储的集合 List<String> fiels = new ArrayList<>(); // 获取结果集的元数据 ResultSetMetaData rsmd = rs.getMetaData(); // 迭代结果集元数据,并且把结果集元数据中的列名提取出来 int len = rsmd.getColumnCount(); for (int i = 0; i < len; i++) { String fiel = rsmd.getColumnLabel(i + 1); fiels.add(fiel); } while (rs.next()) { // 通过class创建构造函数 Constructor<T> constructor = clazz.getDeclaredConstructor(); // 创建实例 T t = constructor.newInstance(); for (String fiel : fiels) { // 从列名中找到相对想的fiel的属性 Object val = rs.getObject(fiel); // 从map中取出属性描述符 PropertyDescriptor bd = bdsMap.get(underlineToCamel(fiel)); // 设置到目标方法上 Method method = bd.getWriteMethod(); // 通过反射给目标方法设置 method.invoke(t, convert(val, bd)); } results.add(t); } } catch (Exception e) { // e.printStackTrace(); LOGGER.error("创建数据库载体失败"); } return results; } } /** * 把下划线命名转换成驼峰式命名 */ private static String underlineToCamel(String str) { String[] strs = str.split("_"); str = ""; for (int i = 0; i < strs.length; i++) { String string = strs[i]; if (i >= 1) { String head = strs[i].substring(0, 1); String food = strs[i].substring(1, strs[i].length()); head = head.toUpperCase(); string = head + food; } str += string; } return str; } /** * 根据属性描述符的类型,强制转换类型 */ private static Object convert(Object val, PropertyDescriptor pd) { // 返回成员属性的类型 Class<?> pdType = pd.getPropertyType(); if (pdType == Integer.class) { return ((Number) val).intValue(); } else if (pdType == Long.class) { return ((Number) val).longValue(); } else if (pdType == Float.class) { return ((Number) val).floatValue(); } else if (pdType == Double.class) { return ((Number) val).doubleValue(); } return val; } /** * 获取Connection */ public static Connection getConnection(String driver, String url, String username, String password) { Connection conn = null; try { // 获取数据库驱动 Class.forName(driver); conn = DriverManager.getConnection(url, username, password); } catch (Exception e) { throw new RuntimeException("获取数据库失败"); } return conn; } public static Connection getConnection(String url, String username, String password) { return getConnection(DRIVER, url, username, password); } /** * 关闭数据库链接 */ public static void close(Connection conn) { if (conn != null) { try { conn.close(); } catch (SQLException e) { // e.printStackTrace(); LOGGER.error("关闭数据库载体失败"); } } } /** * 数据库的增删改 */ public static int update(boolean antuClose, Connection conn, String sql, Object... args) { PreparedStatement ps = null; int len = 0; try { ps = conn.prepareStatement(sql); for (int i = 0; i < args.length; i++) { Object obj = args[i]; ps.setObject(i + 1, obj); } len = ps.executeUpdate(); } catch (SQLException e1) { // e1.printStackTrace(); LOGGER.error("数据库更新失败"); } finally { if (antuClose) { close(conn); } } return len; } public static int update(Connection conn, String sql, Object... args) { return update(false, conn, sql, args); } }
EmployeeDAO(DAO接口):
package com.employee.mysql; import java.util.List; /** * DAO:Data Access Object,数据存取对象 * * @author liuguangfa * */ public interface EmployeeDAO { // /** // * 数据库保存添加一个员工 // * // * @return // */ // boolean addEmployee(Employee employee); /** * 数据库冲保存多条员工信息 */ int addEmployee(List<Employee> employeeList); /** * 删除员工(名字) */ boolean deleteEmployee(String name); /** * 删除员工(id) */ boolean deleteEmployee(int id); /** * 查询所有员工 */ List<Employee> findAll(); /** * 按照姓名查询 */ List<Employee> findByName(String name); /** * 根据id 查询指定的员工 */ List<Employee> finById(int id); /** * 修改员工姓名 */ boolean replaceByName(String newName, int id); /** * 修改员工的年龄 */ boolean replaceByAge(String newAge, int id); /** * 修改员工的性别 */ boolean replaceBysex(String newSex, int id); }
EmployeeDAOimpl(DAO的实现类):
package com.employee.mysql; import java.sql.Connection; import java.util.List; import com.employee.mysql.JdbcUtils.ResuleSetHenderImpl; public class EmployeeDAOimpl implements EmployeeDAO { private final static ResuleSetHenderImpl<Employee> HANDLER = new ResuleSetHenderImpl<>(Employee.class); // // 增加一个员工 // @Override // public boolean addEmployee(Employee employee) { // boolean bool = false; // Connection conn = Global.getConnection(); // String sql = "insert into t_employee(id,name,sex,age) values (?,?,?,?)"; // int len = JdbcUtils.update(true, conn, sql, employee.getId(), employee.getName(), employee.getSex(), // employee.getAge()); // if (len > 0) { // bool = true; // } // return bool; // } // 往数据库中存多条数据(id自动生成,年龄、姓名、性别) @Override public int addEmployee(List<Employee> employees) { Connection conn = Global.getConnection(); int count = 0; for (Employee employee : employees) { String sql = "insert into t_employee(name,sex,age) values (?,?,?)"; count = JdbcUtils.update( conn, sql, employee.getName(), employee.getSex(), employee.getAge()); } JdbcUtils.close(conn); return count; } // 删除员工(通过名字) @Override public boolean deleteEmployee(String name) { boolean bool = false; Connection conn = Global.getConnection(); String sql = "delete from t_employee where name = ?"; int len = JdbcUtils.update(true, conn, sql, name); if (len > 0) { bool = true; } return bool; } // 删除员工(通过id) @Override public boolean deleteEmployee(int id) { boolean bool = false; Connection conn = Global.getConnection(); String sql = "delete from t_employee where id = ?"; int len = JdbcUtils.update(true, conn, sql, id); if (len > 0) { bool = true; } return bool; } // 查询所有的员工信息 @Override public List<Employee> findAll() { Connection conn = Global.getConnection(); String sql = "select * from t_employee"; return JdbcUtils.query(true, conn, sql, HANDLER); } // 查询指定姓名的的员工 @Override public List<Employee> findByName(String name) { Connection conn = Global.getConnection(); String sql = "select * from t_employee where name = ?"; return JdbcUtils.query(true, conn, sql, HANDLER, name); } // 查询指定id的员工 @Override public List<Employee> finById(int id) { Connection conn = Global.getConnection(); String sql = "select * from t_employee where id = ?"; return JdbcUtils.query(true, conn, sql, HANDLER, id); } // 修改员工的姓名(通过id) @Override public boolean replaceByName(String newName, int id) { boolean bool = false; Connection conn = Global.getConnection(); String sql = "update t_employee set name = ? where id = ?"; int len = JdbcUtils.update(true, conn, sql, newName, id); if (len > 0) { bool = true; } return bool; } // 修改员工的年龄(通过id) @Override public boolean replaceByAge(String newAge, int id) { boolean bool = false; Connection conn = Global.getConnection(); String sql = "update t_employee set Age = ? where id = ?"; int len = JdbcUtils.update(true, conn, sql, newAge, id); if (len > 0) { bool = true; } return bool; } // 修改员工的性别(通过id) @Override public boolean replaceBysex(String newSex, int id) { boolean bool = false; Connection conn = Global.getConnection(); String sql = "update t_employee set sex = ? where id = ?"; int len = JdbcUtils.update(true, conn, sql, newSex, id); if (len > 0) { bool = true; } return bool; } }
Logger(日志接口):
package com.employee.mysql; /** * 日志管理器 * * @author liuguangfa * */ public interface Logger { public void error(String message, Exception e); public void error(String message); }
SetLogger(日志接口的实现类):
package com.employee.mysql; import com.lgf.shejimoshi.Logger; /** * 日志管理类实现类 * * @author liuguangfa * */ public class SetLogger implements Logger { @Override public void error(String message, Exception e) { System.out.println(message + ":" + e); } @Override public void error(String message) { System.out.println(message); } }
本文作者:刘广法,转载注明出处。