因为我的电脑安装mysql的时候总是报错,所以我选择了XAMPP作为桥梁来连接mysql,免安装mysql:
链接:https://pan.baidu.com/s/1XYX0hMXCHVbYlDueGv_K4g
提取码:65t8
安装可以参考该博客:https://www.cnblogs.com/liuhongfeng/p/4206044.html
pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.2.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>springboot</artifactId><version>0.0.1-SNAPSHOT</version><name>springboot</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional> <!-- 这个需要为 true 热部署才有效 与build层同时设置才会生效,下面已有注释 --></dependency><!-- mybatis --><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.1.1</version></dependency><!-- mysql --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!-- servlet依赖. --><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><scope>provided</scope></dependency><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId></dependency><!-- tomcat的支持.--><dependency><groupId>org.apache.tomcat.embed</groupId><artifactId>tomcat-embed-jasper</artifactId><scope>provided</scope></dependency><!-- https://mvnrepository.com/artifact/org.json/json --><dependency><groupId>org.json</groupId><artifactId>json</artifactId><version>20190722</version></dependency><!-- Spring Boot Web 依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- thymeleaf 依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><!-- 没有该配置,devtools 不生效 --><fork>true</fork><addResources>true</addResources></configuration></plugin></plugins></build></project>
application.yml
spring:
# mvc:
# view:
# prefix: /WEB-INF/views/
# suffix: .jspthymeleaf:mode: HTMLencoding: UTF-8prefix: classpath:/templates/suffix: .htmlservlet:content-type: text/htmlcache: false #开发时关闭缓存,不然没法看到实时页面datasource:url: jdbc:mysql://localhost:3306/hello?generateSimpleParameterMetadata=true&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=trueusername: hellopassword: hellodriver-class-name: com.mysql.cj.jdbc.Driver #6.0中 需要指定时区serverTimezone#在设定时区的时候,如果设定serverTimezone=UTC,会比中国时间早8个小时,如果在中国,可以选择Asia/Shanghai或者Asia/Hongkong#com.mysql.jdbc.Driver 5.0中 --
server:port: 8383servlet:context-path: /jkmybatis:typeAliasesPackage: com.example.entity #本来打算写两种形式注解跟xml文件的 还没有完成mapperLocations: classpath:mapper/*.xml
logging:file:path: D:/springboot #这是我的项目路径name: springboot.logmax-size: 10MB
SQL
SELECT * CREATE TABLE class (class_id int(32) NOT NULL, class_name varchar(32), remark varchar(128), PRIMARY KEY (class_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE user (remark varchar(128), student_id int(32), class_id int(32), name varchar(32), id int NOT NULL AUTO_INCREMENT, PRIMARY KEY (id)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
from class;
---我用的软件导出来的SQL就这样了,大家可以参考一下
目录结构
com.example.controller
package com.example.controller;import com.example.dao.UserDao;
import com.example.entity.User;
import com.example.service.UserService;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;@Controller
@RequestMapping(value="/user")
public class UserRestController {private final Logger logger = LoggerFactory.getLogger(getClass());@Autowiredprivate UserService userService;private static final String USER_LIST = "StuList";private static final String USER_FORM = "StuForm";private static final String ERROR = "error";private static final String REDIRECT_TO_USER_LIST = "redirect:/user";@RequestMapping(method = RequestMethod.GET,value = "/list")public String showList(ModelMap map){map.addAttribute("UserLIst",userService.showList());return USER_LIST;}/*** 获取用户列表* 通过"/user"GET请求获取* @param map* @return*/@RequestMapping(method=RequestMethod.GET)public String showAll(ModelMap map) {map.addAttribute("UserList",userService.showAll());map.addAttribute("User",new User());map.addAttribute("action", "selectByName");return USER_LIST;}/**** @param user* @return*/@RequestMapping(value="/selectByName",method=RequestMethod.GET)public String selectByUserName(@ModelAttribute User user, ModelMap map){String name = user.getNAME();Integer id = user.getID();logger.info("参数:" +"{" + name +"|"+ id +"}");map.addAttribute("User",new User());map.addAttribute("action", "selectByName");if(StringUtils.isEmpty(name) && "".equals(id) || null ==id) {map.addAttribute("UserList",userService.showAll());} else if(!StringUtils.isEmpty(name) && "".equals(id)|| null == id) {map.addAttribute("UserList",userService.selectByName(name));}else if(StringUtils.isEmpty(name) && !"".equals(id)){map.addAttribute("UserList",userService.selectByID(id.toString()));}return USER_LIST;}/*** 获取创建UserForm表单* @param map* @return*/@RequestMapping(value="/addUser",method=RequestMethod.GET)public String createUserForm(ModelMap map) {User user = new User();logger.info("打开添加页面,返回参数:" + user + " 返回action : addUser" );map.addAttribute("user", user);map.addAttribute("action", "addUser");return USER_FORM;}@RequestMapping(value="/addUser",method=RequestMethod.POST)public String postUser(@ModelAttribute User user) {logger.info("添加学生参数 : " + user);userService.addUser(user);return REDIRECT_TO_USER_LIST;}@RequestMapping(value="/updateByID/{id}",method=RequestMethod.GET)public String getByUserID(@PathVariable String id, ModelMap map) {JSONObject obj = new JSONObject();User result = userService.selectByID(id);if(result ==null) {obj.put("obj",result);obj.put("result","未查到对应数据");Object[] ll = {obj,obj};logger.error("ERROR:"+obj);logger.error("ERROR:{}", obj);//占位符logger.error("ERROR:{}, hah:{}", ll);//占位符 如果需要传递三个或更多参数,则还可以使用Object []变体return ERROR;} else {obj.put("result","查询到对应数据为:" + result);logger.info("SUCCESS:"+obj);map.addAttribute("user",result);map.addAttribute("action","updateByID");return USER_FORM;}}@RequestMapping(value="/updateByID",method=RequestMethod.POST)public String putByUserID(@ModelAttribute User user) {logger.info("修改学生参数 : " + user);userService.updateByUserID(user);return REDIRECT_TO_USER_LIST;}@RequestMapping(value="/deleteByID/{id}",method=RequestMethod.GET)public String deleteUserByID(@PathVariable String id) {logger.info("删除学生参数 : " + id);userService.deleteByUserID(id);return REDIRECT_TO_USER_LIST;}
}
com.example.dao
package com.example.dao;import com.example.entity.User;
import org.apache.ibatis.annotations.*;import java.util.List;@Mapper // 标志为 Mybatis 的 Mapper
public interface UserDao {/*** xml文件配置的查询*/List<User> showList();/*** 列出所有用户信息** @param*/@Select("SELECT a.id,a.student_id,a.name,b.class_name,a.remark FROM user a LEFT JOIN class b ON a.class_id = b.class_id WHERE a.class_id = b.class_id")// 返回所有User信息@Results({@Result(property = "ID", column = "ID"),@Result(property = "STUDENTID", column = "STUDENT_ID"),@Result(property = "NAME", column = "NAME"),@Result(property = "CLASSNAME", column = "CLASS_NAME")})List<User> showAll();/*** 根据Name查询用户信息* @param name* @return*/@Select("SELECT a.id,a.student_id,a.name,b.class_name,a.class_id,a.remark FROM user a LEFT JOIN class b ON a.class_id = b.class_id WHERE a.class_id = b.class_id and a.name=#{NAME}")//根据UserName查询User信息@Results({@Result(property = "ID", column = "ID"),@Result(property = "STUDENTID", column = "STUDENT_ID"),@Result(property = "NAME", column = "NAME"),@Result(property = "CLASSNAME", column = "CLASS_NAME")})List<User> selectByName(String name);//根据UserID查询User信息@Select("SELECT a.id,a.student_id,a.name,b.class_name,a.class_id,a.remark FROM user a LEFT JOIN class b ON a.class_id = b.class_id WHERE a.class_id = b.class_id and a.id=#{ID}")@Results({@Result(property = "ID", column = "ID"),@Result(property = "STUDENTID", column = "STUDENT_ID"),@Result(property = "NAME", column = "NAME"),@Result(property = "CLASSID", column = "CLASS_ID"),@Result(property = "CLASSNAME", column = "CLASS_NAME")})User selectByID(String id);/*** 插入新User* @param user* @return*/
// @SelectKey(keyProperty = "ID",keyColumn="ID",resultType = String.class, before =true, statement = "select max(id) from user" )
// @Options(keyProperty = "ID", useGeneratedKeys = true)@Insert("INSERT INTO user(name,class_id,student_id)"+ " VALUES(#{NAME},#{CLASSID},#{STUDENTID})")
// @Results({
// @Result(property = "id", column = "UserID"),
// @Result(property = "name", column = "UserName"),
// @Result(property = "birthday", column = "UserBirth"),
// @Result(property = "description", column = "Descript")})public void addUser(User user);/*** 根据用户ID更新用户信息(ID唯一标识)* @param user*/@Update("UPDATE user SET name = #{NAME},class_id = #{CLASSID},student_id = #{STUDENTID} WHERE id = #{ID}")@Results({@Result(property = "ID", column = "ID"),@Result(property = "NAME", column = "NAME"),@Result(property = "CLASSID", column = "CLASS_ID"),@Result(property = "STUDENTID", column = "STUDENT_ID")})public void updateByUserID(User user);/*** 根据用户ID删除用户信息(ID唯一标识)* @param id* @return*/@Delete("DELETE FROM user WHERE id=#{ID}")public void deleteByUserID(String id);
}
com.example.entity
package com.example.entity;import java.io.Serializable;public class User implements Serializable {private static final long serialVersionUID = 2019121115;private Integer ID;private String NAME;private String CLASSNAME;private String CLASSID;private Integer STUDENTID;public Integer getID() {return ID;}public void setID(Integer ID) {this.ID = ID;}public String getNAME() {return NAME;}public void setNAME(String NAME) {this.NAME = NAME;}public String getCLASSNAME() {return CLASSNAME;}public void setCLASSNAME(String CLASSNAME) {this.CLASSNAME = CLASSNAME;}public String getCLASSID() {return CLASSID;}public void setCLASSID(String CLASSID) {this.CLASSID = CLASSID;}public Integer getSTUDENTID() {return STUDENTID;}public void setSTUDENTID(Integer STUDENTID) {this.STUDENTID = STUDENTID;}@Overridepublic String toString() {return "User{" +"ID=" + ID +", NAME='" + NAME + '\'' +", CLASSNAME='" + CLASSNAME + '\'' +", CLASSID='" + CLASSID + '\'' +", STUDENTID=" + STUDENTID +'}';}
}
com.example.service
package com.example.service;import com.example.entity.User;import java.util.List;public interface UserService {/*** 列出所有用户信息 xml*/List<User> showList();/*** 列出所有用户信息*/List<User> showAll();/*** 根据用户名称查询用户信息*/List<User> selectByName(String name);/*** 增加用户信息* @return*/User selectByID(String id);// User selectByName(String name);public void addUser(User user);/*** 根据UserID更新用户信息*/public void updateByUserID(User user);
// /**
// * 根据UserName更新用户信息
// */
// public void updateByUserName(User user);/*** 根据UserID删除用户信息* @param id* @return*/public void deleteByUserID(String id);/*** 根据UserName删除用户信息* @param name* @return*/
// public void deleteByUserName(String name);
//
}
com.example.service.impl
package com.example.service.impl;import com.example.dao.UserDao;
import com.example.entity.User;
import com.example.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;/*** UserService逻辑实现类**/
@Service("UserService")
public class UserServiceImpl implements UserService {private static final Logger LOGGER= LoggerFactory.getLogger(UserServiceImpl.class);@Autowiredprivate UserDao userDao;// @Resource
// private RedisServiceImpl redisService;/*** 获取User逻辑:如缓存存在则从换从取值,否则从DB中获取,插入缓存*/public List<User> showList() {return userDao.showList();}public List<User> showAll() {return userDao.showAll();}public List<User> selectByName(String name){return userDao.selectByName(name);}public User selectByID(String id) {User user=userDao.selectByID(id);return user;}public void addUser(User user){userDao.addUser(user);}public void updateByUserID(User user) {userDao.updateByUserID(user);}public void deleteByUserID(String id) {userDao.deleteByUserID(id);}
}
springboot\src\main\resources\static\css
/* contentDiv */
.contentDiv {padding:50px 100px;}
.form-control-chaxun {display: block;height: 34px;padding: 6px 12px;font-size: 14px;line-height: 1.42857143;color: #555;background-color: #fff;background-image: none;border: 1px solid #ccc;border-radius: 4px;-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075);box-shadow: inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
}
springboot\src\main\resources\templates\Error.html
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.w3.org/1999/xhtml">
<!--
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
-->
<head><script type="text/javascript" th:src="@{https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js}"></script><link th:href="@{https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css}" rel="stylesheet"/><link th:href="@{/css/default.css}" rel="stylesheet"/><link rel="icon" th:href="@{/image/205311905.jpg}" type="image/x-icon"/><meta charset="UTF-8"/><title>学生列表</title>
</head><body><div class="contentDiv">
未查询到该ID对应的学生,请联系管理员检查 <a th:href="@{/user}">返回主页面</a>
</div>
</body>
<body></body>
StuForm.html
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.w3.org/1999/xhtml">
<head><script type="text/javascript" th:src="@{https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js}"></script><link th:href="@{https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css}" rel="stylesheet"/><link th:href="@{/css/default.css}" rel="stylesheet"/><link rel="icon" th:href="@{/image/205311905.jpg}" type="image/x-icon"/><meta charset="UTF-8"/><title>学生管理</title>
</head><body>
<div class="contentDiv"><h3>新增学生</h3><form th:action="@{/user/{action}(action=${action})}" method="post" class="form-horizontal"><!--<input type="hidden" id="user_id" name="id" th:value="${user.ID}" th:field="*{user.ID}"/>--><div class="form-group" hidden><label for="user_name" class="col-sm-2 control-label">编号:</label><div class="col-xs-4"><input type="text" class="form-control" id="user_id" name="id" th:value="${user.ID}" th:field="*{user.ID}"/></div></div><div class="form-group"><label for="user_name" class="col-sm-2 control-label">姓名:</label><div class="col-xs-4"><input type="text" class="form-control" id="user_name" name="name" th:value="${user.NAME}" th:field="*{user.NAME}"/></div></div><div class="form-group"><label for="user_birth" class="col-sm-2 control-label">班级:</label><div class="col-xs-4"><input type="text" class="form-control" id="user_birth" name="birthday" th:value="${user.CLASSID}" th:field="*{user.CLASSID}"/></div></div><div class="form-group"><label for="user_birth" class="col-sm-2 control-label">学号:</label><div class="col-xs-4"><input type="text" class="form-control" id="studentid" name="studentid" th:value="${user.STUDENTID}" th:field="*{user.STUDENTID}"/></div></div><div class="form-group"><div class="col-sm-offset-2 col-sm-10"><input class="btn btn-primary" type="submit" value="提交" onclick="user/updateByID"/><input class="btn" type="button" value="返回" onclick="history.back()"/></div></div></form>
</div>
</body>
</html>
StuList.html
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.w3.org/1999/xhtml">
<!--
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
-->
<head><script type="text/javascript" th:src="@{https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js}"></script><link th:href="@{https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css}" rel="stylesheet"/><link th:href="@{/css/default.css}" rel="stylesheet"/><link rel="icon" th:href="@{/image/205311905.jpg}" type="image/x-icon"/><meta charset="UTF-8"/><title>学生列表</title>
</head><body><div class="contentDiv"><h5 style="font-size: xx-large"><strong> 学生管理系统</strong></h5><form th:action="@{/user/{action}(action=${action})}" th:object="${User}" method="get" ><div class="form-group"><div ><label class="col-sm-2 control-label">学生编号</label><input style="width:30%;float:left;margin-right: 20px" name="id" class="form-control-chaxun" id="id" type="text" th:field="*{ID}" placeholder="请输入用户名..." /></div><div ><label class="col-sm-2 control-label">学生名称</label><input style="width:30%;float:left;margin-right: 20px" name="username" class="form-control-chaxun" id="username" type="text" th:field="*{NAME}" placeholder="请输入用户名..." /></div></div><div class="form-group"><div class="col-sm-offset-2 col-sm-10" style="width: 100%;float: right"><input type="submit" value="查询" class="btn btn-danger"/><td style="width:20%;float:right;"><a class="btn btn-primary" th:href="@{/user/addUser}" role="button" style="margin-right:15px;">新增用户</a></td></div></div></form><table class="table table-hover table-condensed" style="margin-top: 20px"><thead ><tr ><th>学生学号</th><th>学生名称</th><th>学生班级</th></tr></thead><tbody><tr th:each="user : ${UserList}"><td style="width:50px;" th:text="${user.ID}" hidden></td><td style="width:100px;" th:text="${user.STUDENTID}"></td><th style="width:100px;" th:text="${user.NAME}"></th><td style="width:120px;" th:text="${user.CLASSNAME}"></td><td style="width:50px;"><a class="btn btn-danger" th:href="@{/user/deleteByID/{id}(id=${user.ID})}">删除</a><a class="btn btn-danger" th:href="@{/user/updateByID/{id}(id=${user.ID})}">更新</a></td></tr></tbody></table>
</div>
</body>
<body></body>
参考文献 https://blog.csdn.net/satan91/article/details/80958925