1、配置文件 pom.xml、application.properties
<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.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.1.15.RELEASEversion>
<relativePath/>
parent>
<groupId>cn.lemongroupId>
<artifactId>demoartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>demoname>
<description>Demo project for Spring Bootdescription>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.1.1version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
<version>1.1.10version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
## 端口
server.port=8080
##数据源配置
##连接池类型
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
##数据库驱动
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
##数据库
spring.datasource.url=jdbc:mysql://localhost:3306/db_users?useUnicode=true&characterEncoding=utf8
##用户名
spring.datasource.username=root
##密码
spring.datasource.password=root
##MyBatis配置
mybatis.mapper-locations=classpath*:mybatis/*.xml
mybatis.type-aliases-package=cn.lemon.demo.entity
#配置访问静态文件
spring.mvc.static-path-pattern=/static/**
#thymelea模板配置
#默认页面映射路径
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
#热部署文件,页面不产生缓存,及时更新。关闭模板缓存
spring.thymeleaf.cache=false
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
2、实体类 User.java
package cn.lemon.demo.entity;
import lombok.Data;
import java.io.Serializable;
@Data
public class User implements Serializable {
private Integer id;
private String name;
private String sex;
private int age;
private String address;
}
3、数据访问层 IUserDao.java、映射文件 IUserDao.xml
package cn.lemon.demo.dao;
import cn.lemon.demo.entity.User;
import java.util.List;
public interface IUserDao {
int insertUser(User user);
int deleteUserById(Integer id);
int updateUser(User user);
User selectUserById(Integer id);
List<User> selectAllUser();
List<User> selectAllUserByName(String name);
}
<mapper namespace="cn.lemon.demo.dao.IUserDao">
<sql id="key">
<trim suffixOverrides=",">
<if test="name != null and name != ''">
name,
if>
<if test="sex != null and sex != ''">
sex,
if>
<if test="age != null">
age,
if>
<if test="address != null and address != ''">
address,
if>
trim>
sql>
<sql id="values">
<trim suffixOverrides=",">
<if test="name != null and name != ''">
#{name},
if>
<if test="sex != null and sex != ''">
#{sex},
if>
<if test="age != null">
#{age},
if>
<if test="address != null and address != ''">
#{address},
if>
trim>
sql>
<insert id="insertUser" parameterType="cn.lemon.demo.entity.User">
insert into user (<include refid="key"/>) values (<include refid="values"/>);
insert>
<delete id="deleteUserById" parameterType="Integer">
delete from user where id = #{id};
delete>
<update id="updateUser" parameterType="cn.lemon.demo.entity.User">
UPDATE user
<set>
<if test="name != null and name.trim() != ''">
name = #{name},
if>
<if test="sex != null and sex.trim() != ''">
sex = #{sex},
if>
<if test="age != null">
age = #{age},
if>
<if test="address != null and address.trim() != ''">
address = #{address},
if>
set>
WHERE id = #{id}
update>
<select id="selectUserById" parameterType="Integer" resultType="cn.lemon.demo.entity.User">
select * from user where id = #{id}
select>
<select id="selectAllUser" resultType="cn.lemon.demo.entity.User">
select * from user
select>
<select id="selectAllUserByName" resultType="cn.lemon.demo.entity.User">
select * from user where name like '%${name}%'
select>
mapper>
4、业务逻辑层接口 IUserService.java、实现类 UserServiceImpl.java
package cn.lemon.demo.service;
import cn.lemon.demo.entity.User;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public interface IUserService {
int insertUser(User user);
int deleteUserById(Integer id);
int updateUser(User user);
User selectUserById(Integer id);
List<User> selectAllUser();
List<User> selectAllUserByName(String name);
}
package cn.lemon.demo.service.impl;
import cn.lemon.demo.dao.IUserDao;
import cn.lemon.demo.entity.User;
import cn.lemon.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private IUserDao userDao;
@Override
public int insertUser(User user) {
return userDao.insertUser(user);
}
@Override
public int deleteUserById(Integer id) {
return userDao.deleteUserById(id);
}
@Override
public int updateUser(User user) {
return userDao.updateUser(user);
}
@Override
public User selectUserById(Integer id) {
return userDao.selectUserById(id);
}
@Override
public List<User> selectAllUser() {
return userDao.selectAllUser();
}
@Override
public List<User> selectAllUserByName(String name) {
return userDao.selectAllUserByName(name);
}
}
5、业务逻辑层测试类 UserServiceImplTest.java
package cn.lemon.demo.service.impl;
import cn.lemon.demo.entity.User;
import cn.lemon.demo.service.IUserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import static org.junit.Assert.*;
@SpringBootTest
@RunWith(SpringRunner.class)
public class UserServiceImplTest {
@Autowired
private IUserService userService;
@Test
public void insertUser() {
User user = new User();
user.setName("汤普森");
user.setSex("男");
user.setAge(28);
user.setAddress("金州勇士");
userService.insertUser(user);
}
@Test
public void deleteUserById() {
userService.deleteUserById(8);
}
@Test
public void updateUser() {
User u = new User();
u.setId(4);
u.setSex("男");
u.setAddress("洛杉矶湖人");
u.setAge(38);
u.setName("詹姆斯");
userService.updateUser(u);
}
@Test
public void selectUserById() {
User user = userService.selectUserById(7);
System.out.println(user.getAddress());
}
@Test
public void selectAllUser() {
List<User> userList = userService.selectAllUser();
for (User user : userList) {
System.out.println(user.getName() + user.getAddress());
}
}
@Test
public void selectAllUserByName() {
List<User> userList = userService.selectAllUserByName("兰");
for (User user : userList) {
System.out.println(user.getName() + user.getAddress());
}
}
}
6、控制层 UserController.java
package cn.lemon.demo.controller;
import cn.lemon.demo.entity.User;
import cn.lemon.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService userService;
//跳转页面
@RequestMapping("/")
public String index() {
return "index";
}
//查询所有
@RequestMapping(value = "/userList", method = RequestMethod.GET)
@ResponseBody
public Object userList() {
List<User> userList = userService.selectAllUser();
return userList;
}
//根据 ID 查询用户
@RequestMapping(value = "/findById/{id}", method = RequestMethod.GET)
@ResponseBody
public Object findById(@PathVariable("id") Integer id) {
return userService.selectUserById(id);
}
//添加用户
@RequestMapping(value = "/add", method = RequestMethod.GET)
@ResponseBody
public Object addUser(@Valid User user) {
int i = userService.insertUser(user);
//System.out.println(user.getName() + user.getAddress());
return user;
}
//根据 ID 删除用户
@DeleteMapping("/delete/{id}")
public void delete(@PathVariable("id") Integer id) {
userService.deleteUserById(id);
}
//根据 ID 修改用户
@PutMapping("/update/{id}")
@ResponseBody
public Object update(@PathVariable("id") Integer id,
@RequestParam("name") String name,
@RequestParam("sex") String sex,
@RequestParam("age") Integer age,
@RequestParam("address") String address) {
User user = new User();
user.setId(id);
user.setName(name);
user.setAge(age);
user.setSex(sex);
user.setAddress(address);
userService.updateUser(user);
return user;
}
//根据 name 查询
@RequestMapping(value = "/selectUserByUsername", method = RequestMethod.GET)
@ResponseBody
public Object selectUserByUsername(@RequestParam("name") String name) {
//System.out.println(name);
List<User> users = userService.selectAllUserByName(name);
return users;
}
}
1、index.html(需要引入 Jquery)
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>用户title>
<script type="text/javascript" th:src="@{/static/js/jquery.min.js}">script>
<script type="text/javascript" th:src="@{/static/js/index.js}">script>
head>
<body>
<div id="showUser">
<h2 id="hid">用户列表h2>
<div id="inputId">
<input id="selectByNameInput" type="text" placeholder="请输入用户名">
<input id="selectByName" onclick="selectByUserName()" type="button" value="查询">    
<input id="insert" onclick="insertUser()" type="button" value="添加用户">
div>
<br>
<div id="head">
<table>
<thead>
<tr>
<th>编号th>
<th>姓名th>
<th>性别th>
<th>年龄th>
<th>地址th>
<th id="cz">操作th>
tr>
thead>
<tbody id="tbody">
tbody>
table>
div>
<div id="show">
div>
div>
body>
html>
2、index.js
//查询所有
$(function () {
var tbody = document.getElementById("tbody");
$.ajax({
type: "get",
url: '/user/userList',
contentType: "application/json;charset=utf-8",
dataType: 'json',
async: false,
success: function (data) {
//清空数据
$("#tbody").html('');
//追加数据
for (var i = 0; i < data.length; i++) {
$("#tbody").append("" +
"" + data[i].id + " " +
"" + data[i].name + " " +
"" + data[i].sex + " " +
"" + data[i].age + " " +
"" + data[i].address + " " +
" + data[i].id + ")'/>" + " " +
" + data[i].id + ")'/> " +
" ");
}
},
error: function () {
window.alert("查询失败");
}
});
});
//修改用户回显数据
function updateUser(id) {
//var show = document.getElementById("show");
$("#hid").text("修改用户");//把用户列表改为修改用户
$("#head").hide();//隐藏
$("#inputId").hide();//隐藏
$.ajax({
type: "get",
url: '/user/findById/' + id,
contentType: "application/json;charset=utf-8",
dataType: 'json',
async: false,
success: function (data) {
//清空数据
//$("#tbody").html('');
//追加数据
$("#show").append(
"编号:
" +
"姓名:
" +
"性别:
" +
"年龄:
" +
"地址:
" +
" + data.id + ")'>");
},
error: function () {
window.alert("无法修改");
}
})
}
//修改用户
function update(id) {
var name = $("input[name='name']").val();
var sex = $("input[name='sex']").val();
var age = $("input[name='age']").val();
var address = $("input[name='address']").val();
$.ajax({
url: '/user/update/' + id,
type: "put",
async: false,
data: {
"name": name, "sex": sex, "age": age, "address": address},
success: function () {
$("#name").val(name);
$("#sex").val(sex);
$("#age").val(age);
$("#address").val(address);
alert("修改成功");
window.location.reload();
},
error: function () {
alert("修改失败");
}
});
}
//删除用户
function deleteUser(id) {
$.ajax({
type: "delete",
url: "/user/delete/" + id,
//dataType: JSON,
async: false,
success: function () {
window.location.reload();
alert("删除成功");
},
error: function () {
alert("删除失败");
}
});
};
//添加用户显示输入框
function insertUser() {
//var show = document.getElementById("show");
$("#hid").text("添加用户");//把用户列表改为修改用户
$("#head").hide();//隐藏
$("#inputId").hide();//隐藏
$.ajax({
success: function () {
//追加数据
$("#show").append(
"姓名:
" +
"性别:
" +
"年龄:
" +
"地址:
" +
"");
},
error: function () {
window.alert("无法添加");
}
})
}
//添加用户
function insertByUser() {
var name = $("input[name='name']").val();
var sex = $("input[name='sex']").val();
var age = $("input[name='age']").val();
var address = $("input[name='address']").val();
$.ajax({
url: '/user/add',
type: "get",
//dataType: JSON,
data: {
"name": name, "sex": sex, "age": age, "address": address},
success: function () {
window.alert("添加成功");
window.location.reload();
},
error: function () {
window.alert("添加失败");
}
});
};
//根据 name 模糊查询
function selectByUserName() {
var name = $("input[id='selectByNameInput']").val();
$.ajax({
type: "get",
url: '/user/selectUserByUsername',
contentType: "application/json;charset=utf-8",
//dataType: 'json',
data: {
"name": name},
async: false,
success: function (data) {
//清空数据
$("#tbody").html('');
//追加数据
for (var i = 0; i < data.length; i++) {
$("#tbody").append("" +
"" + data[i].id + " " +
"" + data[i].name + " " +
"" + data[i].sex + " " +
"" + data[i].age + " " +
"" + data[i].address + " " +
" + data[i].id + ")'/>" + " " +
" + data[i].id + ")'/> " +
" ");
}
},
error: function () {
window.alert("查询失败");
}
});
}