一、创建项目包 package

  1. 文件夹命名全部小写
  2. mvc:
  3. com.entity
  4. 放和表对应的实体类
  5. com.dao
  6. 数据访问层不做业务处理
  7. 判断逻辑
  8. 数据转换
  9. com.service
  10. 业务层接口 业务层做业务处理
  11. com.service.impl
  12. 业务层接口实现类
  13. com.controller
  14. 控制层代码
  15. test.com.controller
  16. 控制层代码测试
  17. test.com.dao
  18. 数据访问层测试
  19. test.com.entity
  20. 实体类层测试

二、创建雇员表

  1. CREATE TABLE `t_employee` (
  2. `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  3. `addTime` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '入库时间',
  4. `birthday` datetime DEFAULT NULL COMMENT '出生日期',
  5. `ename` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '员工姓名',
  6. `position` varchar(225) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '位置',
  7. `tel` varchar(225) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '电话',
  8. `addr` varchar(225) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '地址',
  9. `school` varchar(225) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '学校',
  10. `sex` varchar(225) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '性别',
  11. PRIMARY KEY (`id`)
  12. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;

三、创建雇员实体类

  1. package com.entity;
  2. import java.util.Date;
  3. /**
  4. * 雇员
  5. */
  6. public class Employee {
  7. //主键ID
  8. private Long id;
  9. //入库时间
  10. private Date addTime;
  11. //出生日期
  12. private Date birthday;
  13. //员工姓名
  14. private String ename;
  15. //电话
  16. private String tel;
  17. //地址
  18. private String addr;
  19. //学校
  20. private String school;
  21. //性别
  22. private String sex;
  23. public Long getId() {
  24. return id;
  25. }
  26. public void setId(Long id) {
  27. this.id = id;
  28. }
  29. public Date getAddTime() {
  30. return addTime;
  31. }
  32. public void setAddTime(Date addTime) {
  33. this.addTime = addTime;
  34. }
  35. public Date getBirthday() {
  36. return birthday;
  37. }
  38. public void setBirthday(Date birthday) {
  39. this.birthday = birthday;
  40. }
  41. public String getEname() {
  42. return ename;
  43. }
  44. public void setEname(String ename) {
  45. this.ename = ename;
  46. }
  47. public String getTel() {
  48. return tel;
  49. }
  50. public void setTel(String tel) {
  51. this.tel = tel;
  52. }
  53. public String getAddr() {
  54. return addr;
  55. }
  56. public void setAddr(String addr) {
  57. this.addr = addr;
  58. }
  59. public String getSchool() {
  60. return school;
  61. }
  62. public void setSchool(String school) {
  63. this.school = school;
  64. }
  65. public String getSex() {
  66. return sex;
  67. }
  68. public void setSex(String sex) {
  69. this.sex = sex;
  70. }
  71. }

四、添加JDBC 驱动包、junit测试包

G@L()4ZZ71U$GDBFULBJ(GC.png
){BH7L$0{HUTD%~BNP)BSNR.png

五、创建db.properties数据库配置文件

在src下面创建db.properties

  1. driver=com.mysql.cj.jdbc.Driver
  2. url=jdbc:mysql://localhost:3306/erp
  3. userName=root
  4. password=root

六、创建DBUtils

  1. package com.utils;
  2. import java.io.BufferedInputStream;
  3. import java.io.FileInputStream;
  4. import java.io.InputStream;
  5. import java.sql.Connection;
  6. import java.sql.DriverManager;
  7. import java.sql.SQLException;
  8. import java.util.Properties;
  9. /**
  10. * 数据库访问 工具类
  11. */
  12. public class DBUtils {
  13. //ctrl+shift+u
  14. //默认值是null
  15. public static String DRIVER;
  16. public static String URL;
  17. public static String USERNAME;
  18. public static String PASSWORD;
  19. /**
  20. * 在这个工具包第一次使用的时候就会加载这一块
  21. * 只要程序不停止,就是一次在内存中的
  22. * 可以通过类名直接调用等方式
  23. */
  24. static {
  25. try{
  26. InputStream in = new BufferedInputStream(new FileInputStream("src/db.properties")) ;
  27. Properties p = new Properties();
  28. p.load(in);
  29. DRIVER =p.getProperty("driver");
  30. URL =p.getProperty("url");
  31. USERNAME =p.getProperty("userName");
  32. PASSWORD =p.getProperty("password");
  33. Class.forName(DRIVER);
  34. }catch (Exception e){
  35. e.printStackTrace();
  36. }
  37. }
  38. /**
  39. * 获得数据库连接
  40. * @return
  41. */
  42. public static Connection getConn(){
  43. try{
  44. Connection conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);
  45. return conn;
  46. }catch (Exception e){
  47. e.printStackTrace();
  48. throw new RuntimeException("数据库连接报错:"+e.getMessage());//告诉调用方这里报错了
  49. }finally {
  50. // System.out.println("....");
  51. }
  52. //这里执行不到
  53. //return null;
  54. }
  55. /**
  56. * 关闭数据库连接
  57. * @param conn
  58. */
  59. public static void close(Connection conn){
  60. try{
  61. if(conn != null){
  62. conn.close();
  63. }
  64. }catch (SQLException e){
  65. e.printStackTrace();
  66. throw new RuntimeException(e.getMessage());//告诉调用方这里报错了
  67. }
  68. }
  69. public static void main(String[] args) {
  70. System.out.println(DBUtils.DRIVER);
  71. }
  72. }

七、创建数据访问层dao

  1. package com.dao;
  2. import com.entity.Employee;
  3. import com.utils.DBUtils;
  4. import java.sql.*;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. /**
  8. * 员工 数据访问层
  9. * 新增、修改、查询、删除、分页
  10. */
  11. public class EmployeeDao {
  12. /**
  13. * INSERT INTO `erp`.`t_employee` (`id`, `addTime`, `birthday`, `ename`, `tel`, `addr`, `school`, `sex`)
  14. * VALUES ('2', '2022-04-13 10:07:00', '2022-04-13 10:07:00', '老王同学', '1234567890', '福州市区。。。', '高中', '男');
  15. * 新增雇员
  16. * @param emp
  17. * @return 新增的行数
  18. */
  19. public int insert(Employee emp){
  20. try{
  21. //获得连接
  22. Connection conn = DBUtils.getConn();
  23. //拼装SQL语句
  24. StringBuilder sql = new StringBuilder();
  25. sql.append(" insert into t_employee(birthday,ename,tel,addr,school,sex) ");
  26. sql.append(" values(?,?,?,?,?,?) ");
  27. //获得预编译执行
  28. PreparedStatement stmt = conn.prepareStatement(sql.toString());
  29. //设置参数
  30. stmt.setTimestamp(1,new Timestamp(emp.getBirthday().getTime()));
  31. stmt.setString(2,emp.getEname());
  32. stmt.setString(3,emp.getTel());
  33. stmt.setString(4,emp.getAddr());
  34. stmt.setString(5,emp.getSchool());
  35. stmt.setString(6,emp.getSex());
  36. //执行update 新增操作 返回新增的行数
  37. int c = stmt.executeUpdate();
  38. return c;
  39. }catch (SQLException e){
  40. e.printStackTrace();
  41. throw new RuntimeException(e.getMessage());
  42. }
  43. }
  44. /**
  45. *
  46. update t_employee set
  47. addTime = '2022-4-13 10:03:09',
  48. birthday = '2022-4-13 10:02:01',
  49. ename = '小张同学',
  50. tel = '123451234512',
  51. addr = '深圳市罗湖区...',
  52. school = '中学',
  53. sex='男'
  54. where id = 1
  55. -----------------------------------
  56. UPDATE `erp`.`t_employee` SET `id`='2', `addTime`='2022-04-13 10:07:00', `birthday`='2022-04-13 10:07:00',
  57. `ename`='老王同学', `tel`='1234567890', `addr`='福州市区。。。', `school`='高中', `sex`='男' WHERE (`id`='2');
  58. *
  59. * 基于ID进行 修改 属性
  60. * @param emp
  61. * @return
  62. */
  63. public int updateById(Employee emp){
  64. try{
  65. //获得连接
  66. Connection conn = DBUtils.getConn();
  67. //拼装SQL语句
  68. StringBuilder sql = new StringBuilder();
  69. sql.append(" update t_employee set ");
  70. sql.append(" addTime = ?, ");
  71. sql.append(" birthday = ?, ");
  72. sql.append(" ename = ?, ");
  73. sql.append(" tel = ?, ");
  74. sql.append(" addr = ?, ");
  75. sql.append(" school = ?, ");
  76. sql.append(" sex= ? ");
  77. sql.append(" where id = ? ");
  78. //获得预编译执行
  79. PreparedStatement stmt = conn.prepareStatement(sql.toString());
  80. //设置参数
  81. stmt.setTimestamp(1,new Timestamp(new java.util.Date().getTime()));
  82. stmt.setTimestamp(2,new Timestamp(emp.getBirthday().getTime()));
  83. stmt.setString(3,emp.getEname());
  84. stmt.setString(4,emp.getTel());
  85. stmt.setString(5,emp.getAddr());
  86. stmt.setString(6,emp.getSchool());
  87. stmt.setString(7,emp.getSex());
  88. stmt.setLong(8,emp.getId());
  89. //执行update 修改操作 返回修改的行数
  90. int c = stmt.executeUpdate();
  91. return c;
  92. }catch (SQLException e){
  93. e.printStackTrace();
  94. throw new RuntimeException(e.getMessage());
  95. }
  96. }
  97. /**
  98. * 根据ID查询 雇员
  99. * @param id
  100. * @return
  101. */
  102. public Employee getById(Long id){
  103. try{
  104. //获得连接
  105. Connection conn = DBUtils.getConn();
  106. //拼装SQL语句
  107. StringBuilder sql = new StringBuilder();
  108. sql.append(" select id,addTime,birthday,ename,tel,addr,school,sex ");
  109. sql.append(" from t_employee where id = ? ");
  110. //获得预编译执行
  111. PreparedStatement stmt = conn.prepareStatement(sql.toString());
  112. //设置参数
  113. stmt.setLong(1,id);
  114. //执行Query
  115. ResultSet rs = stmt.executeQuery();
  116. //用来接收返回值
  117. Employee emp = new Employee();
  118. //判断是否有下一行
  119. while(rs.next()){
  120. emp.setId(rs.getLong("id"));
  121. emp.setAddTime(rs.getTimestamp("addTime"));
  122. emp.setBirthday(rs.getTimestamp("birthday"));
  123. emp.setEname(rs.getString("ename"));
  124. emp.setTel(rs.getString("tel"));
  125. emp.setAddr(rs.getString("addr"));
  126. emp.setSchool(rs.getString("school"));
  127. emp.setSex(rs.getString("sex"));
  128. }
  129. return emp;
  130. }catch (SQLException e){
  131. e.printStackTrace();
  132. throw new RuntimeException(e.getMessage());
  133. }
  134. }
  135. /**
  136. -- select * from t_employee limit (current - 1) * pageSize,pageSize
  137. -- m:从0开始的位置
  138. -- n:返回多少条
  139. -- pageSize 每页10条
  140. -- 第一页
  141. select * from t_employee limit (1 -1 ) * 10,10
  142. -- 第二页
  143. select * from t_employee limit (2 -1 ) * 10,10
  144. -- 第三页
  145. select * from t_employee limit (3 - 1) * 10,10
  146. * @param current 第几页的页码
  147. * @param pageSize 每页多少条数据
  148. * @return
  149. */
  150. public List<Employee> page(Integer current,Integer pageSize){
  151. try{
  152. //获得连接
  153. Connection conn = DBUtils.getConn();
  154. //拼装SQL语句
  155. StringBuilder sql = new StringBuilder();
  156. sql.append(" select id,addTime,birthday,ename,tel,addr,school,sex ");
  157. sql.append(" from t_employee limit ?,? ");
  158. //获得预编译执行
  159. PreparedStatement stmt = conn.prepareStatement(sql.toString());
  160. //设置参数
  161. stmt.setInt(1,(current - 1) * pageSize);
  162. stmt.setInt(2,pageSize);
  163. //执行Query
  164. ResultSet rs = stmt.executeQuery();
  165. //用来接收返回值
  166. List<Employee> emps = new ArrayList<>();
  167. //判断是否有下一行
  168. while(rs.next()){
  169. //每一次创建一个新的Employee
  170. Employee emp = new Employee();
  171. emp.setId(rs.getLong("id"));
  172. emp.setAddTime(rs.getTimestamp("addTime"));
  173. emp.setBirthday(rs.getTimestamp("birthday"));
  174. emp.setEname(rs.getString("ename"));
  175. emp.setTel(rs.getString("tel"));
  176. emp.setAddr(rs.getString("addr"));
  177. emp.setSchool(rs.getString("school"));
  178. emp.setSex(rs.getString("sex"));
  179. //添加到List集合中
  180. emps.add(emp);
  181. }
  182. return emps;
  183. }catch (SQLException e){
  184. e.printStackTrace();
  185. throw new RuntimeException(e.getMessage());
  186. }
  187. }
  188. }

八、创建测试类

  1. package test.com.dao;
  2. import com.dao.EmployeeDao;
  3. import com.entity.Employee;
  4. import com.utils.DBUtils;
  5. import org.junit.Test;
  6. import static org.junit.Assert.*;
  7. import java.util.Date;
  8. import java.util.List;
  9. /**
  10. * 测试雇员数据访问层
  11. */
  12. public class TestEmployeeDao {
  13. //成员对象 在成员方法中可以直接访问到
  14. EmployeeDao employeeDao = new EmployeeDao();
  15. @Test
  16. public void testInsert(){
  17. Employee emp = new Employee();
  18. emp.setBirthday(new Date());
  19. emp.setAddr("福州市区。。。");
  20. emp.setEname("小王同学");
  21. emp.setSchool("小学5年级");
  22. emp.setSex("女");
  23. emp.setTel("1234567890");
  24. for (int i = 0; i < 50; i++) {
  25. int c = employeeDao.insert(emp);
  26. assertEquals(c,1);
  27. }
  28. }
  29. @Test
  30. public void testUpdate(){
  31. Employee emp = new Employee();
  32. emp.setId(2L);
  33. emp.setBirthday(new Date());
  34. emp.setAddr("福州市区。。。");
  35. emp.setEname("老王同学");
  36. emp.setSchool("高中");
  37. emp.setSex("男");
  38. emp.setTel("1234567890");
  39. int c = employeeDao.updateById(emp);
  40. assertEquals(c,1);
  41. }
  42. @Test
  43. public void testGetById(){
  44. Long id = 3L;
  45. Employee emp = employeeDao.getById(id);
  46. assertNotNull(emp.getId());
  47. System.out.println(emp.getId());
  48. }
  49. @Test
  50. public void testPage(){
  51. //前台:网页 小程序 app
  52. Integer current = 10;
  53. //每页多少条有的后台给定好的 也有的前台传过来的
  54. Integer pageSize = 10;
  55. List<Employee> emps = employeeDao.page(current,pageSize);
  56. for (Employee emp : emps) {
  57. System.out.println("id = " + emp.getId() + " ename = " + emp.getEname());
  58. }
  59. }
  60. }