用idea反向生成实现对数据库的增删改查
先简单实现数据库的增加
第一步:先定义一个接口,在这个接口中初步定义需要的增删改查方法。
/**
* 声明service
*/
public interface TeamService {
void Add(Team team);//声明方法用来描述行为或动作
}
第二步:定义一个类,实现第一步定义的接口中的方法
/**
* 实现对应的接口,具体实现接口声明的方法
*/
@Service("teamService")//标记他是一个服务,请Spring帮我们管理
public class TeamServiceImpl implements TeamService {
//自动注入,让spring 实例化赋值给他
@Autowired
private TeamMapper teamMapper;
@Override
public void Add(Team team) {
teamMapper.insertSelective(team);//调用mapper中的方法,进行相关的数据库操作
}
}
第三步,定义一个controller类,在controller类中先声明一个接口的变量,然后定义一个方法用来接收前端传回来的值,最后用接口的变量调用实现了接口的类中的方法,添加成功
package com.qcby.controller;
import com.qcby.entity.Team;
import com.qcby.service.TeamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller//标记它是一个控制器
@RequestMapping("team")//设置这个类请求识别的url
public class TeamController {
@Autowired//自动注入,请spring帮我们实例化
private TeamService teamService;
@RequestMapping("teamAdd")//设置这个方法请求识别的url
public String teamAdd(Model model,Team team){//参数中的team是spring 帮我们自动填充属性 请求中参数名要和team中的域名字一致才行
teamService.Add(team);//调用服务中方法 用来插入这个实例
model.addAttribute("msg","添加成功");//设置model的属性,以便于视图处理
return "edu/teamList";//和前缀后缀共同拼写得到页面的路径,spring mvc回去找到文件
}
@RequestMapping("goTeamAdd")//在前端页面先在URL中输入这个地址,跳转添加数据需要输入的页面,在页面中在将数据返回给上面方法
public String goTeamAdd(){
return "edu/index";
}
}
第四步,设计一个jsp页面,用来给controller传值
<%--
Created by IntelliJ IDEA.
User: kevinlyz
Date: 2019-05-19
Time: 11:48
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%-- form表单提交
将数据返回给注解为teamAdd的方法
--%>
<form action="<%=request.getContextPath()%>/team/teamAdd" method="post">
<input name="major" type="text"/>
<input name="tnumber" type="text"/>
<input name="tname" type="text"/>
<input type="submit" value="确定">
</form>
</body>
</html>
第五步,上面添加成功后,跳转一个成功页面
<%--
Created by IntelliJ IDEA.
User: heaboy
Date: 2019-05-19
Time: 19:43
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}<!--EL表达式 获取model中设置的属性 -->
</body>
</html>
文件格式
类和mapping为之前反向生成的