增加数据主要涉及四个文件
Apple.java写清楚数据库内部字段
package com.example.appledemo.pojo;
import lombok.Getter;
@Getter
public class Apple {
private Integer appleId;
private Integer price;
private Integer weight;
public void setAppleId(Integer appleId) {
this.appleId = appleId;
}
public void setPrice(Integer price) {
this.price = price;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
}
AppleMapper写sql语句
package com.example.appledemo.mapper;
import com.example.appledemo.pojo.Apple;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface AppleMapper {
@Select("SELECT * FROM apple")
List<Apple> findAll();
@Insert("INSERT INTO apple (appleId, price, weight) VALUES (#{appleId}, #{price}, #{weight})")
void insertApple(Apple apple);
}
TestController指定页面
package com.example.appledemo.controller;
import com.example.appledemo.mapper.AppleMapper;
import com.example.appledemo.mapper.UserMapper;
import com.example.appledemo.pojo.Apple;
import com.example.appledemo.pojo.User;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.Model;
import java.util.ArrayList;
import java.util.List;
@Controller
public class TestController {
@Resource
UserMapper userMapper;
@Resource
AppleMapper appleMapper;
@RequestMapping("/test")
public ModelAndView test(){
ModelAndView modelAndView=new ModelAndView();
modelAndView.setViewName("hello");
List<String> list=new ArrayList<String>();
list.add("yyy");
list.add("aaa");
list.add("bbb");
modelAndView.addObject("list",list);
return modelAndView;
}
@RequestMapping("/login")
public String login(Model model){
List<User> user = userMapper.findAll();
model.addAttribute("user",user);
return "login";
}
@RequestMapping("/apple")
public String apple(Model model){
List<Apple> apple = appleMapper.findAll();
model.addAttribute("apple",apple);
return "apple";
}
@RequestMapping("/insertPage")
public String insertPage(){
return "insertPage";
}
@RequestMapping("/insert")
public String insert(Apple apple){
appleMapper.insertApple(apple);
System.out.println("新增了苹果");
return "redirect:/apple";
}
}
insertPage
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>添加用户</title>
<link href="/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div style="width:800px;height:100%;margin-left:270px;">
<form action="/insert" method="post">
用户名:<input class="form-control" type="text" th:value="${price}" name="price"><br>
密 码:<input class="form-control" type="text" th:value="${weight}" name="weight"><br>
<button class="btn btn-primary btn-lg btn-block">保存</button>
</form>
</div>
</body>
</html>
运行结果: