使用springboot实现CRUD操作


新建项目

新建一个项目,选择spring initializr项目



Thymeleaf热部署,选不选都OK,这里还用不到。

项目创建完成。

准备工作

application.properties配置文件

#数据源配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useSSL=false&useUnicode=true&characterEncoding=utf-8&autoReconnect=true&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.initialSize=20
spring.datasource.minIdle=50
spring.datasource.maxActive=500#上下文配置
server.port=8888
server.servlet.context-path=/Student#配置jpa
#帮我们自动生成表结构
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true

创建一个数据库,看到上面url中我的是springboot,需要更改为自己的。
创建一个表studentdemo,设置id递增

pom.xml添加依赖

        <!-- druid数据库连接池--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.10</version></dependency><!--分页--><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>1.2.10</version></dependency>

程序代码

项目结构

创建实体类
entity/Student
字段对应数据库

package com.example.denmo.student.entity;import javax.persistence.*;@Entity
//代表实体类
@Table(name = "studentdemo")
//注解对应数据库表名
public class Student {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private int id;private String name;private String sex;private String password;public Student(int id, String name, String sex, String password) {this.id = id;this.name = name;this.sex = sex;this.password = password;}public Student() {super();}@Overridepublic String toString() {return "Student{" +"id=" + id +", name='" + name + '\'' +", sex='" + sex + '\'' +", password='" + password + '\'' +'}';}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}
}

DAO层
StuDao
继承JpaRepository类

package com.example.denmo.student.dao;import com.example.denmo.student.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;//JpaRepository支持接口规范方法名查询。意思是如果在接口中定义的查询方法符合它的命名规则,就可以不用写实现
//JpaRepository<Student,Integer> 接口 两个参数第一个为实体类型,第二个为主键类型
public interface StuDao extends JpaRepository<Student,Integer> {//自定义sql,登陆方法@Query(name = "login",nativeQuery = true,value ="select * from studentdemo where name=:name and password=:password ")Student login(@Param("name") String name, @Param("password") String password);
}

Service层
StuService

package com.example.denmo.student.service;import com.example.denmo.student.entity.Student;
import org.springframework.data.domain.Page;public interface StuService {Student findStuByID(int id);//根据id查询用户Student save(Student student);//保存、添加用户Student update(Student student);//修改用户void delete(int id);//删除用户Student login(String name,String password);//登陆Page<Student> findAll(int page,int pagesize);//分页}

实现stuservice

StuServiceimpl

package com.example.denmo.student.service;import com.example.denmo.student.dao.StuDao;
import com.example.denmo.student.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
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;@Service
public class StuServiceimpl implements StuService {@Autowiredprivate StuDao stuDao;@Overridepublic Student findStuByID(int id) {return stuDao.getOne(id);}@Overridepublic Student save(Student student) {return stuDao.save(student);}@Overridepublic Student update(Student student) {return stuDao.save(student);}@Overridepublic void delete(int id) {stuDao.deleteById(id);}/*父类中没有login方法,所以要自定义sql。Studao中定义.*/@Overridepublic Student login(String name, String password) {return stuDao.login(name,password);}@Override/*要注意Page分页全部选择org.springframework.data.domain下的*/public Page<Student> findAll(int page, int pagesize) {//设置id升序排列Pageable pageable = PageRequest.of(page,pagesize,new Sort(Sort.Direction.ASC,"id"));return stuDao.findAll(pageable);}
}

控制层
StuController

package com.example.denmo.student.controller;import com.example.denmo.student.entity.Student;
import com.example.denmo.student.service.StuService;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletResponse;/*** 处理学生信息控制层* @author 醒醒,醒醒**/
@RestController
@RequestMapping("/stu")
public class StuController {@Autowiredprivate StuService stuService;/*** 根据id查询用户* @param id* @return*/@RequestMapping("/findStuById")public Student findStuById(int id){return stuService.findStuByID(id);}/*** 用户注册方法* @param student* @return*/@RequestMapping("/registerStu")public Student registerStu(Student student){return stuService.save(student);}/*** 修改学生* @param student* @return*/@RequestMapping("/updateStu")public Student updateStu(Student student){return stuService.update(student);}/*** 删除用户* @param id* @return*/@GetMapping("/deleteStu")public String deleteStu(int id){stuService.delete(id);return "Deleted";}/*** 登陆* @param name* @param password* @return*/@GetMapping("/loginStu")public Student loginStu(String name,String password){return stuService.login(name,password);}/*** 分页查询* @param p* @param response* @return*/@GetMapping("/queryStu")public Page<Student> findByPage(Integer p, HttpServletResponse response){response.setHeader("Access-Control-Allow-Origin","*");//设置响应头。if(p==null||p<0){p = 0;}else {p -= 1;}return stuService.findAll(p,5);//设置为每次查询五个}}

所用注解总结:

1、RestController 应用在Controller层的类上面2、RequestMapping("/xxx") ,@RequestMapping(value = "/findAll",method = RequestMethod.POST)3、@Entity  应用在实体类上4、@Table(name = "user") 应用在实体类上5、@Id@GeneratedValue(strategy = GenerationType.IDENTITY) 应用在实体类中的ID属性上6、@Service 应用在Service实现类上7、@Autowired 用于类中的属性注入8、自定义查询@Query(name="login",nativeQuery = true,value ="select * from user where username=:username and password=:password")

测试

运行项目
这里使用postman工具测试。
注册:

登陆

分页查询

可以看到,传值时还需要以**?属性=值的方式,破坏安全性
使用RESTful规范后代码和原始代码比较

    /*** 根据id查询用户* @param id* @return*/@RequestMapping("/findStuById")public Student findStuById(int id){return stuService.findStuByID(id);}/*** 根据id查询用户* //使用RESTful规范,即不再用 ?传值。注意以下{id}和@PathVariable* @param id* @return*/@RequestMapping("/findStuById/{id}")public Student findStuById(@PathVariable int id){return stuService.findStuByID(id);}


简单前端页面看效果

分页查询


page.html

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title></title><script src="js/jquery.js" type="text/javascript" charset="UTF-8">     </script><script type="text/javascript">var page = 1;var tp = 0;$(function(){showData();});function uppage(){if(page>1){page--;showData();}}function downpage(){if(page<tp){page++;showData();}}function showData(){$.ajax({url:'http://localhost:8888/Student/stu/queryStu?p='+page,success:function(result){var rel = result.content;tp = result.totalPages;var htmlStr = "<table width='80%' algin='center' border='1'>"+"<tr><th>ID</th><th>姓名</th><th>密码</th><th>性别</th><th>操作</th></tr>";for(var i=0;i<rel.length;i++){var stu = rel[i];htmlStr += "<tr><td>"+stu.id+"</td><td>"+stu.name+"</td><td>"+stu.password+"</td><td>"+stu.sex+"</td><td><a href='http://localhost:8888/Student/stu/findStuById/"+stu.id+"'>编辑</a>&nbsp;<a href='http://localhost:8888/Student/stu/deleteStu/"+stu.id+"'>删除</a></td></tr>";}htmlStr += "</table>";$("#show").html(htmlStr);}});}</script></head><body><h1 style="text-align: center;">学生管理系统</h1><div id="show"></div><a href="javascript:uppage()">上一页</a><a href="javascript:downpage()">下一页</a></body>
</html>

登陆
login.html

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>login</title></head><body><h1>登陆</h1><form action="http://localhost:8888/Stu/stu/loginStu" method="get">用户名:<input type="text" name="name"  value="" /><br>密码:<input type="password" name="password" /><br><input type="submit" value="登陆" /></form></body>
</html>

注册
registerStu.html

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>registerStu</title></head><body><h1>注册信息</h1><form action="http://localhost:8888/Stu/stu/register" method="post">用户名:<input type="text" name="name" value="" /><br>密码:<input type="password" name="password" value="" /><br><input type="submit" value="注册" /></form></body>
</html>

springboot--入门程序实现CRUD操作相关推荐

  1. SpringBoot简介、SpringBoot 入门程序搭建、与JDBC、Druid、Mybatis和SpringData JPA的整合

    一.SpringBoot 简介: spring boot并不是一个全新的框架,它不是spring解决方案的一个替代品,而是spring的一个封装.所以,你以前可以用spring做的事情,现在用spri ...

  2. SpringBoot整合MongoDB完成CRUD操作(超详细)

    官方文档:https://www.mongodb.com/docs/manual/reference/connection-string/ 01.导入依赖 <dependency>< ...

  3. springboot入门程序

    (1)设置spring boot的parent <parent> <groupId>org.springframework.boot</groupId> <a ...

  4. core 实例化接口_实例讲解Springboot整合MongoDB进行CRUD操作的两种方式

    1 简介 Springboot是最简单的使用Spring的方式,而MongoDB是最流行的NoSQL数据库.两者在分布式.微服务架构中使用率极高,本文将用实例介绍如何在Springboot中整合Mon ...

  5. sitecore开发入门Sitecore的CRUD操作 - 第一部分

    在本文中,讨论如何使用Sitecore.Data.Items.Item并对这些项执行CRUD(创建,读取,更新和删除)操作.我还将介绍如何使用Glass和Fortis类库进行相同的操作,这些操作都是对 ...

  6. Mybatis入门程序增删改查操作

    学习目标 了解Mybatis的基本知识 熟悉Mybatis的工作原理 掌握Mybatis入门程序的编写 文章目录 1.初始Mybatis 2.Mybatis入门程序 3.Mybatis操作总结 1.初 ...

  7. SpringBoot @Cacheable缓存入门程序

    导语 在之前的博客中分享了关于SpringBoot缓存的一些基本的概念,在这篇博客中提供一个小小的入门的实例,通过这个实例可以更好的了解关于SpringBoot缓存有关的知识点.   首先既然是缓存的 ...

  8. SpringBoot入门操作笔记[+mybatismysql]

    文章目录 SpringBoot入门操作笔记[+mybatis&mysql] 1. 创建工程 1.1. 新建SpringBoot项目 1.2. 配置Maven 1.3. 编码配置 2. 项目结构 ...

  9. 访问其他程序中的数据(ContentResolver的CRUD操作)

    内容提供器的用法一般有两种: 1.使用现有的内容提供器来读取和操作相应程序中的数据 2.创建自己的内容提供器给我们程序的数据提供外部访问接口. 如果一个应用程序通过内容提供器对其数据提供了外部访问接口 ...

  10. 玩转springboot:thymeleaf模板引擎入门程序

    一.前言 常用的模板引擎有:JSP.Velocity.Freemarker.Thymeleaf 但是,Springboot默认是不支持JSP的,默认使用thymeleaf模板引擎.而且,语法更简单,功 ...

最新文章

  1. IDEA设置单个文件、单个包、单个项目的编码格式
  2. python亲和性分析法推荐电影论文_数据挖掘-MovieLens数据集_电影推荐_亲和性分析_Aprioro算法...
  3. 明早1点去青岛,可能要两天不能写博客了
  4. Linux学习之系统编程篇:信号的基本概念
  5. 左神算法:用一个栈实现另一个栈的排序(Java版)
  6. diamond淘宝框架使用
  7. 【渝粤教育】广东开放大学 个人与团队管理 形成性考核 (57)
  8. WIN2003 X64 系统上安装sql server 2000 的步骤
  9. Java笔记-非对称加密RSA的使用
  10. 获取springbean的几种方式
  11. Python3合并ts文件
  12. 关于各类图形CAD底层内核
  13. Power BI数据可视化
  14. (3)paddle---近视眼睛分类的例子
  15. 2016阿里巴巴73款开源产品全向图
  16. 目标与计划:仰望星空且脚踏实地
  17. 杂七杂八(4): win10设置启动时创建系统还原点
  18. Android Runtime.getRuntime().exec()
  19. 信息系统项目管理师核心考点(五十五)配置管理员(CMO)的工作
  20. 机器学习之网格搜索调参sklearn

热门文章

  1. 微信将可开小号!微信内测一个手机可注册俩号
  2. 实时网速怎么看快慢_如何知道网络的实时网速?4种方法轻松查询
  3. XGBOOST从原理到实战:二分类 、多分类
  4. 鸿鹄系统和鸿蒙系统区别,荣耀智慧屏正式发布 鸿蒙系统+鸿鹄818芯片 售价3799元起...
  5. matlab对图片边缘化处理
  6. pgsql删除表中所有数据_pg数据库 删除所有表
  7. java面试问题与心得
  8. 大数据职业理解_大数据岗位介绍和职业规划分析
  9. 批量修改windows 用户密码
  10. 鬼迷心窍 歌词翻译 中译日