一、创建项目包 package
文件夹命名全部小写
mvc:
com.entity
放和表对应的实体类
com.dao
数据访问层不做业务处理
判断逻辑
数据转换
com.service
业务层接口 业务层做业务处理
com.service.impl
业务层接口实现类
com.controller
控制层代码
test.com.controller
控制层代码测试
test.com.dao
数据访问层测试
test.com.entity
实体类层测试
二、创建雇员表
CREATE TABLE `t_employee` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`addTime` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '入库时间',
`birthday` datetime DEFAULT NULL COMMENT '出生日期',
`ename` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '员工姓名',
`position` varchar(225) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '位置',
`tel` varchar(225) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '电话',
`addr` varchar(225) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '地址',
`school` varchar(225) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '学校',
`sex` varchar(225) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '性别',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
三、创建雇员实体类
package com.entity;
import java.util.Date;
/**
* 雇员
*/
public class Employee {
//主键ID
private Long id;
//入库时间
private Date addTime;
//出生日期
private Date birthday;
//员工姓名
private String ename;
//电话
private String tel;
//地址
private String addr;
//学校
private String school;
//性别
private String sex;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getAddTime() {
return addTime;
}
public void setAddTime(Date addTime) {
this.addTime = addTime;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
四、添加JDBC 驱动包、junit测试包
五、创建db.properties数据库配置文件
在src下面创建db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/erp
userName=root
password=root
六、创建DBUtils
package com.utils;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
/**
* 数据库访问 工具类
*/
public class DBUtils {
//ctrl+shift+u
//默认值是null
public static String DRIVER;
public static String URL;
public static String USERNAME;
public static String PASSWORD;
/**
* 在这个工具包第一次使用的时候就会加载这一块
* 只要程序不停止,就是一次在内存中的
* 可以通过类名直接调用等方式
*/
static {
try{
InputStream in = new BufferedInputStream(new FileInputStream("src/db.properties")) ;
Properties p = new Properties();
p.load(in);
DRIVER =p.getProperty("driver");
URL =p.getProperty("url");
USERNAME =p.getProperty("userName");
PASSWORD =p.getProperty("password");
Class.forName(DRIVER);
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 获得数据库连接
* @return
*/
public static Connection getConn(){
try{
Connection conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);
return conn;
}catch (Exception e){
e.printStackTrace();
throw new RuntimeException("数据库连接报错:"+e.getMessage());//告诉调用方这里报错了
}finally {
// System.out.println("....");
}
//这里执行不到
//return null;
}
/**
* 关闭数据库连接
* @param conn
*/
public static void close(Connection conn){
try{
if(conn != null){
conn.close();
}
}catch (SQLException e){
e.printStackTrace();
throw new RuntimeException(e.getMessage());//告诉调用方这里报错了
}
}
public static void main(String[] args) {
System.out.println(DBUtils.DRIVER);
}
}
七、创建数据访问层dao
package com.dao;
import com.entity.Employee;
import com.utils.DBUtils;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* 员工 数据访问层
* 新增、修改、查询、删除、分页
*/
public class EmployeeDao {
/**
* INSERT INTO `erp`.`t_employee` (`id`, `addTime`, `birthday`, `ename`, `tel`, `addr`, `school`, `sex`)
* VALUES ('2', '2022-04-13 10:07:00', '2022-04-13 10:07:00', '老王同学', '1234567890', '福州市区。。。', '高中', '男');
* 新增雇员
* @param emp
* @return 新增的行数
*/
public int insert(Employee emp){
try{
//获得连接
Connection conn = DBUtils.getConn();
//拼装SQL语句
StringBuilder sql = new StringBuilder();
sql.append(" insert into t_employee(birthday,ename,tel,addr,school,sex) ");
sql.append(" values(?,?,?,?,?,?) ");
//获得预编译执行
PreparedStatement stmt = conn.prepareStatement(sql.toString());
//设置参数
stmt.setTimestamp(1,new Timestamp(emp.getBirthday().getTime()));
stmt.setString(2,emp.getEname());
stmt.setString(3,emp.getTel());
stmt.setString(4,emp.getAddr());
stmt.setString(5,emp.getSchool());
stmt.setString(6,emp.getSex());
//执行update 新增操作 返回新增的行数
int c = stmt.executeUpdate();
return c;
}catch (SQLException e){
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
/**
*
update t_employee set
addTime = '2022-4-13 10:03:09',
birthday = '2022-4-13 10:02:01',
ename = '小张同学',
tel = '123451234512',
addr = '深圳市罗湖区...',
school = '中学',
sex='男'
where id = 1
-----------------------------------
UPDATE `erp`.`t_employee` SET `id`='2', `addTime`='2022-04-13 10:07:00', `birthday`='2022-04-13 10:07:00',
`ename`='老王同学', `tel`='1234567890', `addr`='福州市区。。。', `school`='高中', `sex`='男' WHERE (`id`='2');
*
* 基于ID进行 修改 属性
* @param emp
* @return
*/
public int updateById(Employee emp){
try{
//获得连接
Connection conn = DBUtils.getConn();
//拼装SQL语句
StringBuilder sql = new StringBuilder();
sql.append(" update t_employee set ");
sql.append(" addTime = ?, ");
sql.append(" birthday = ?, ");
sql.append(" ename = ?, ");
sql.append(" tel = ?, ");
sql.append(" addr = ?, ");
sql.append(" school = ?, ");
sql.append(" sex= ? ");
sql.append(" where id = ? ");
//获得预编译执行
PreparedStatement stmt = conn.prepareStatement(sql.toString());
//设置参数
stmt.setTimestamp(1,new Timestamp(new java.util.Date().getTime()));
stmt.setTimestamp(2,new Timestamp(emp.getBirthday().getTime()));
stmt.setString(3,emp.getEname());
stmt.setString(4,emp.getTel());
stmt.setString(5,emp.getAddr());
stmt.setString(6,emp.getSchool());
stmt.setString(7,emp.getSex());
stmt.setLong(8,emp.getId());
//执行update 修改操作 返回修改的行数
int c = stmt.executeUpdate();
return c;
}catch (SQLException e){
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
/**
* 根据ID查询 雇员
* @param id
* @return
*/
public Employee getById(Long id){
try{
//获得连接
Connection conn = DBUtils.getConn();
//拼装SQL语句
StringBuilder sql = new StringBuilder();
sql.append(" select id,addTime,birthday,ename,tel,addr,school,sex ");
sql.append(" from t_employee where id = ? ");
//获得预编译执行
PreparedStatement stmt = conn.prepareStatement(sql.toString());
//设置参数
stmt.setLong(1,id);
//执行Query
ResultSet rs = stmt.executeQuery();
//用来接收返回值
Employee emp = new Employee();
//判断是否有下一行
while(rs.next()){
emp.setId(rs.getLong("id"));
emp.setAddTime(rs.getTimestamp("addTime"));
emp.setBirthday(rs.getTimestamp("birthday"));
emp.setEname(rs.getString("ename"));
emp.setTel(rs.getString("tel"));
emp.setAddr(rs.getString("addr"));
emp.setSchool(rs.getString("school"));
emp.setSex(rs.getString("sex"));
}
return emp;
}catch (SQLException e){
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
/**
-- select * from t_employee limit (current - 1) * pageSize,pageSize
-- m:从0开始的位置
-- n:返回多少条
-- pageSize 每页10条
-- 第一页
select * from t_employee limit (1 -1 ) * 10,10
-- 第二页
select * from t_employee limit (2 -1 ) * 10,10
-- 第三页
select * from t_employee limit (3 - 1) * 10,10
* @param current 第几页的页码
* @param pageSize 每页多少条数据
* @return
*/
public List<Employee> page(Integer current,Integer pageSize){
try{
//获得连接
Connection conn = DBUtils.getConn();
//拼装SQL语句
StringBuilder sql = new StringBuilder();
sql.append(" select id,addTime,birthday,ename,tel,addr,school,sex ");
sql.append(" from t_employee limit ?,? ");
//获得预编译执行
PreparedStatement stmt = conn.prepareStatement(sql.toString());
//设置参数
stmt.setInt(1,(current - 1) * pageSize);
stmt.setInt(2,pageSize);
//执行Query
ResultSet rs = stmt.executeQuery();
//用来接收返回值
List<Employee> emps = new ArrayList<>();
//判断是否有下一行
while(rs.next()){
//每一次创建一个新的Employee
Employee emp = new Employee();
emp.setId(rs.getLong("id"));
emp.setAddTime(rs.getTimestamp("addTime"));
emp.setBirthday(rs.getTimestamp("birthday"));
emp.setEname(rs.getString("ename"));
emp.setTel(rs.getString("tel"));
emp.setAddr(rs.getString("addr"));
emp.setSchool(rs.getString("school"));
emp.setSex(rs.getString("sex"));
//添加到List集合中
emps.add(emp);
}
return emps;
}catch (SQLException e){
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
}
八、创建测试类
package test.com.dao;
import com.dao.EmployeeDao;
import com.entity.Employee;
import com.utils.DBUtils;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.Date;
import java.util.List;
/**
* 测试雇员数据访问层
*/
public class TestEmployeeDao {
//成员对象 在成员方法中可以直接访问到
EmployeeDao employeeDao = new EmployeeDao();
@Test
public void testInsert(){
Employee emp = new Employee();
emp.setBirthday(new Date());
emp.setAddr("福州市区。。。");
emp.setEname("小王同学");
emp.setSchool("小学5年级");
emp.setSex("女");
emp.setTel("1234567890");
for (int i = 0; i < 50; i++) {
int c = employeeDao.insert(emp);
assertEquals(c,1);
}
}
@Test
public void testUpdate(){
Employee emp = new Employee();
emp.setId(2L);
emp.setBirthday(new Date());
emp.setAddr("福州市区。。。");
emp.setEname("老王同学");
emp.setSchool("高中");
emp.setSex("男");
emp.setTel("1234567890");
int c = employeeDao.updateById(emp);
assertEquals(c,1);
}
@Test
public void testGetById(){
Long id = 3L;
Employee emp = employeeDao.getById(id);
assertNotNull(emp.getId());
System.out.println(emp.getId());
}
@Test
public void testPage(){
//前台:网页 小程序 app
Integer current = 10;
//每页多少条有的后台给定好的 也有的前台传过来的
Integer pageSize = 10;
List<Employee> emps = employeeDao.page(current,pageSize);
for (Employee emp : emps) {
System.out.println("id = " + emp.getId() + " ename = " + emp.getEname());
}
}
}