springboot+vue+ElementUI+DataJPA快速上手
愿大家都能拥有独立开发的项目能力0.0项目介绍:关于crud的模式数据库设计后端的增删改查接口前端的页面调用crud 下的设计模式:在业务系统中增删改查(crud)是经常需要开发的内容,本文主要从增删改查来对设计模式进行一个学习或使用.一般我们对一个表的增删改查有如下一些接口定义boolean insert(Object o);Object byId(Integer id);boolean del
·
愿大家都能拥有独立开发的项目能力0.0
项目介绍:
- 关于crud的模式
- 数据库设计
- 后端的增删改查接口
- 前端的页面调用
crud 下的设计模式:
- 在业务系统中增删改查(crud)是经常需要开发的内容,本文主要从增删改查来对设计模式进行一个学习或使用.
- 一般我们对一个表的增删改查有如下一些接口定义
boolean insert(Object o);
Object byId(Integer id);
boolean del(Integer id);
boolean editor(Integer interfaces, Object o;
数据库操作:
创建数据库结构
首先我们使用的是简单的User表的设计
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL COMMENT '姓名',
`age` int(11) DEFAULT NULL COMMENT '年龄',
`sex` varchar(1) DEFAULT NULL COMMENT '性别',
`address` varchar(255) DEFAULT NULL COMMENT '地址',
`phone` varchar(20) DEFAULT NULL COMMENT '电话',
`create_time` varchar(20) DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
创建项目只需要勾选四个即可
当然大家也可以使用MybatisPlus 或者JPA都可以 ,Mybatisplus可以不用勾选,在maven中导入mybatisplus依赖即可!!
Spring Boot DevTools
SpringWeb
SpringDataJPA
MySQLDrive
Maven依赖
<dependencies>
<!--添加Springmvc依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- springBoot JPA的起步依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
Entity
package com.example.entity;
import javax.persistence.*;
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer age;
private String sex;
private String address;
private String phone;
@Column(name = "create_time")
private String createTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
}
Dao继承JpaRepository
因为我们使用了JPA,所以DAO实现接口就行,不用写太多的方法
package com.example.dao;
import com.example.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
/*
*带条件的分页查询
*/
@Query(value = "select * from user where name like %?1%", nativeQuery = true)
Page<User> findByNameLike(String name, Pageable pageRequest);
}
Servie层写我们的基本增删改查
package com.example.service;
import com.example.dao.UserRepository;
import com.example.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Service
public class UserService {
@Resource
private UserRepository userRepository;
/**
* 注意!id新增
* 修改不需要id,直接修改
* @param user
*/
public void save(User user) {
String now = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
user.setCreateTime(now);
userRepository.save(user);
}
/**
* 根据id删除
* @param id
*/
public void delete(Long id) {
userRepository.deleteById(id);
}
/**
* 根据id查询
* @param id
* @return
*/
public User findById(Long id) {
return userRepository.findById(id).orElse(null);
}
/**
* 查询全部
* @return
*/
public List<User> findAll() {
return userRepository.findAll();
}
/**
* 分页
* @param pageNum
* @param pageSize
* @param name
* @return
*/
public Page<User> findPage(Integer pageNum, Integer pageSize, String name) {
// 构建分页查询条件
Sort sort = new Sort(Sort.Direction.DESC, "create_time");
Pageable pageRequest = PageRequest.of(pageNum - 1, pageSize, sort);
return userRepository.findByNameLike(name, pageRequest);
}
}
创建一个common包用来存储我们的常用的工具类
前后台分离的Vue项目通常使用ajax或者axios请求返回我们的json数据
那么我们需要一个Result类来返回状态信息 还有一个必要的跨域类WebMvcConfig
package com.example.common;
public class Result<T> {
private String code;
private String msg;
private T data;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Result() {
}
public Result(T data) {
this.data = data;
}
public static Result success() {
Result result = new Result<>();
result.setCode("0");
result.setMsg("成功");
return result;
}
public static <T> Result<T> success(T data) {
Result<T> result = new Result<>(data);
result.setCode("0");
result.setMsg("成功");
return result;
}
public static Result error(String code, String msg) {
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
return result;
}
}
package com.example.common;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 描述:
* 作者: xq
* 日期: 2020/5/8 13:28
**/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedHeaders("Content-Type","X-Requested-With","accept,Origin","Access-Control-Request-Method","Access-Control-Request-Headers","token")
.allowedMethods("*")
.allowedOrigins("*")
.allowCredentials(true);
}
}
yml的配置类 配置了最基本的
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
url: jdbc:mysql://localhost:3306/mytest?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2b8
现在我们的基本配置已经完成,来到我们的vue前端了
包括还有一部分js文件,需要的可以联系我
当然也可以在element官网自己引用 官网地址如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户信息</title>
<!-- 引入样式 -->
<link rel="stylesheet" href="element.css">
</head>
<body>
<div id="app" style="width: 80%; margin: 0 auto">
<h2>用户信息表</h2>
<el-row>
<el-col :span="6" style="margin-bottom: 10px">
<el-button type="primary" @click="add">新增</el-button>
<el-input v-model="name" style="width: 70%" @keyup.enter.native="loadTable(1)"></el-input>
</el-col>
</el-row>
<el-table
:data="page.content"
stripe
border
style="width: 100%">
<el-table-column
prop="name"
label="用户名"
>
</el-table-column>
<el-table-column
prop="age"
label="年龄"
width="180">
</el-table-column>
<el-table-column
prop="sex"
label="性别">
</el-table-column>
<el-table-column
prop="address"
label="地址">
</el-table-column>
<el-table-column
prop="phone"
label="电话">
</el-table-column>
<el-table-column
fixed="right"
label="操作"
width="100">
<template slot-scope="scope">
<el-button type="primary" icon="el-icon-edit" size="small" circle @click="edit(scope.row)"></el-button>
<el-button type="danger" icon="el-icon-delete" size="small" circle @click="del(scope.row.id)"></el-button>
</template>
</el-table-column>
</el-table>
<el-row type="flex" justify="center" style="margin-top: 10px">
<el-pagination
layout="prev, pager, next"
:page-size="pageSize"
:current-page="pageNum"
@prev-click="loadTable"
@current-change="loadTable"
@next-click="loadTable"
:total="page.totalElements">
</el-pagination>
</el-row>
<el-dialog
title="用户信息"
:visible.sync="dialogVisible"
width="30%">
<el-form ref="form" :model="form" label-width="80px">
<el-form-item label="用户名">
<el-input v-model="form.name"></el-input>
</el-form-item>
<el-form-item label="年龄">
<el-input v-model="form.age"></el-input>
</el-form-item>
<el-form-item label="性别">
<el-radio v-model="form.sex" label="男">男</el-radio>
<el-radio v-model="form.sex" label="女">女</el-radio>
</el-form-item>
<el-form-item label="地址">
<el-input v-model="form.address"></el-input>
</el-form-item>
<el-form-item label="电话">
<el-input v-model="form.phone"></el-input>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="save">确 定</el-button>
</span>
</el-dialog>
</div>
<script src="jquery.min.js"></script>
<script src="vue.js"></script>
<!-- 引入组件库 -->
<script src="element.js"></script>
<script>
new Vue({
el: '#app',
data: {
page: {},
name: '',
pageNum: 1,
pageSize: 8,
dialogVisible: false,
form: {}
},
created() {
this.loadTable(this.pageNum);
},
methods: {
loadTable(num) {
this.pageNum = num;
$.get("/user/page?pageNum=" + this.pageNum + "&pageSize=" + this.pageSize + "&name=" + this.name).then(res => {
this.page = res.data;
});
},
add() {
this.dialogVisible = true;
this.form = {};
},
edit(row) {
this.form = row;
this.dialogVisible = true;
},
save() {
let data = JSON.stringify(this.form);
if (this.form.id) {
// 编辑
$.ajax({
url: '/user',
type: 'put',
contentType: 'application/json',
data: data
}).then(res => {
this.dialogVisible = false;
this.loadTable(1);
})
} else {
// 新增
$.ajax({
url: '/user',
type: 'post',
contentType: 'application/json',
data: data
}).then(res => {
this.dialogVisible = false;
this.loadTable(1);
})
}
},
del(id) {
$.ajax({
url: '/user/' + id,
type: 'delete',
contentType: 'application/json'
}).then(res => {
this.loadTable(1);
})
}
}
})
</script>
</body>
</html>
Control层的编写
package com.example.controller;
import com.example.common.Result;
import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
// 新增用户
@PostMapping
public Result add(@RequestBody User user) {
userService.save(user);
return Result.success();
}
// 修改用户
@PutMapping
public Result update(@RequestBody User user) {
userService.save(user);
return Result.success();
}
// 删除用户
@DeleteMapping("/{id}")
public void delete(@PathVariable("id") Long id) {
userService.delete(id);
}
// 根据id查询用户
@GetMapping("/{id}")
public Result<User> findById(@PathVariable Long id) {
return Result.success(userService.findById(id));
}
// 查询所有用户
@GetMapping
public Result<List<User>> findAll() {
return Result.success(userService.findAll());
}
// 分页查询用户
@GetMapping("/page")
public Result<Page<User>> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
@RequestParam(defaultValue = "10") Integer pageSize,
@RequestParam(required = false) String name) {
return Result.success(userService.findPage(pageNum, pageSize, name));
}
}
感谢大家观看!!
更多推荐
已为社区贡献1条内容
所有评论(0)