部门表
id 主键 自增
name 部门名称
location 部门地址
员工表 t_employee
id 主键 自增
name 员工姓名
sex 员工性别
registerDate 入职日期 date
dept_id 部门编号 外键 引用了部门表的主键
所用技术
jsp + servlet + springboot + springJdbc + druid + mysql
- 创建数据库表 及 测试数据(每张表 3条以上) 10分
- 实体类 5分
- 完成列表 50分
- 完成删除 10分 其中 js完成提示5分
- 完成添加 10分
- 完成修改 15分 其中5分是回显
sql脚本
CREATE TABLE `dept` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`location` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
insert into `dept`(`id`,`name`,`location`) values (1,'研发部','北京'),(2,'销售部','上海'),(3,'公关部','南京');
CREATE TABLE `emp` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`sex` varchar(50) DEFAULT NULL,
`registerDate` date DEFAULT NULL,
`dept_id` int(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `dept_id` (`dept_id`),
CONSTRAINT `emp_ibfk_1` FOREIGN KEY (`dept_id`) REFERENCES `dept` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
实现思路
1.bean员工对象设置部门属性
这样在springjdbc查询时,可查出员工及部门信息,将部门信息放入部门对象中,再将部门对象放入员工对象,实现封装信息。
部门表
2.查询员工信息方法
此处就是创建员工和部门对象,部门对象封装好信息后,再将自己封装进员工对象中,前端只用取自己需要的信息显示。
public List<Emp> findAllEmp() {
String sql="select d.id did,d.name dname,d.location,e.id,e.name,e.sex,e.registerDate from emp e,dept d where e.dept_id=d.id;";
List<Emp> emps = jt.query(sql, new RowMapper<Emp>() {
@Override
public Emp mapRow(ResultSet resultSet, int i) throws SQLException {
Emp emp = new Emp();
Dept dept = new Dept();
emp.setId(resultSet.getInt("id"));
emp.setName(resultSet.getString("name"));
emp.setSex(resultSet.getString("sex"));
emp.setRegisterDate(resultSet.getString("registerDate"));
dept.setId(resultSet.getInt("did"));
dept.setName(resultSet.getString("dname"));
dept.setLocation(resultSet.getString("location"));
emp.setDept(dept);
return emp;
}
});
return emps;
}
3.添加员工方法
添加员工需要添加以下信息
此处多了部门id,我们可以从员工对象中的部门属性中获取部门id
public int insertEmp(Emp emp) {
//1 张三 男 1982-2-2 开发部 北京
String sql="insert into emp values(null,?,?,?,?);";
int update = jt.update(sql, emp.getName(), emp.getSex(), emp.getRegisterDate(), emp.getDept().getId());
return update;
}
4.修改员工信息方法
修改员工时,要有修改条件,即修改哪一条员工信息,所以点击修改时,需要将员工name传过去,以name为修改条件
<a href="update.jsp?name=${emp.name}&sex=${emp.sex}®isterDate=${emp.registerDate}&dept_id=${emp.dept.id}">修改</a>
如何获取dept_id,从部门属性的id中获取
public int updateEmp(Emp emp,String aaa) {
// 姓名 性别 入职日期 所属部门
String sql="update emp set name=?,sex=?,registerDate=?,dept_id=? where name=?;";
int update = jt.update(sql, emp.getName(), emp.getSex(), emp.getRegisterDate(), emp.getDept().getId(),aaa);
return update;
}
5.删除员工信息方法
删除哪个员工,需要传给后端删除条件,这里以员工name作为条件。
另外,删除时需要给出确认框是否删除,引入confirm()方法,确定删除返回true,否则返回false,就可以实现true提交访问路径实现删除,false不提交路径,不做操作。
<a href="/main?method=delete&name=${emp.name}" onclick="return confirm('是否删除')">删除</a>
public int deleteEmp(String name) {
String sql="delete from emp where name=?";
int update = jt.update(sql, name);
return update;
}