亲宝软件园·资讯

展开

Springboot Jpa CRUD Springboot和Jpa实现学生CRUD操作代码实例

Dream0000 人气:0

前期准备

使用idea新建个SpringBoot项目

在数据库中建student表

建包

1.编写entity包下实体类Student

(一个Javabean规范)

package com.example.stu.kudestu.stu.entity;

import javax.persistence.*;

@Entity
@Table(name = "student")
//@Entity 应用在实体类上  @Table(name = "student") 应用在实体类上,并且name属性为数据库表名
public class Student {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY) //ID自增
  private Integer id;
  private String name;
  private int age;
  private String sex;

  @Override
  public String toString() {
    return "Student{" +
        "id=" + id +
        ", name='" + name + '\'' +
        ", age=" + age +
        ", sex='" + sex + '\'' +
        '}';
  }

  public Student() {
  }

  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 int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public String getSex() {
    return sex;
  }

  public void setSex(String sex) {
    this.sex = sex;
  }
}

2.编写dao层StudentDao类

package com.example.stu.kudestu.stu.dao;

import com.example.stu.kudestu.stu.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface StudentDao extends JpaRepository<Student,Integer> {
//<Student,Integer>两个参数实体类和主键类型
  Student findStuById(Integer id);
 @Query(name="findStuByName",nativeQuery = true,value =
      "select * from student where name=:name ")
  List<Student> findStuByName(@Param("name") String name);
}

3.编写service层类StudentService,面象接口

import com.example.stu.kudestu.stu.entity.Student;
import org.springframework.data.domain.Page;
import java.util.List;


public interface StudentService {
  Student save(Student student);//添加学生
  Student update(Student student);//修改
  void delete(Integer id);//通过id删除学生
  Student findStuById(Integer id);//通过ID查找学生,接口中没有此方法,在StudentDao接口创建
  List<Student> findStuByName(String name);//通过学生姓名查找,在StudentDao接口创建

  /**
   * 分页查询所有数据
   * @param page //当前页
   * @param pageSize //每页记录数
   * @return
   */
  Page<Student> findAll(int page,int pageSize);

}

在service对接口实现

import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceimpl implements StudentService {

  @Autowired//用于类中的属性注入
  private StudentDao studentDao;


  @Override
  public Student save(Student student) {
    return studentDao.save(student);
  }

  @Override
  public Student update(Student student) {
    return studentDao.save(student);
  }

  @Override
  public void delete(Integer id) {
    studentDao.deleteById(id);
  }

  @Override
  public Student findStuById(Integer id) {
    return studentDao.findStuById(id);
  }

  @Override
  public List<Student> findStuByName(String name) {
    return studentDao.findStuByName(name);
  }

  @Override
  public Page<Student> findAll(int page,int pageSize) {
    Pageable pageable= PageRequest.of(page,pageSize);
    return studentDao.findAll(pageable);

  }
}

4.编写Controller层StudentController类

package com.example.stu.kudestu.stu.controller;

import com.example.stu.kudestu.stu.dao.StudentDao;
import com.example.stu.kudestu.stu.entity.Student;
import com.example.stu.kudestu.stu.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController 
/*应用在Controller层的类上面
@RequestMapping("/s")
public class StudentController {

  @Autowired//依赖注入
  private StudentService studentService;

  /**
   * 添加学生
   * @param student 要添加学生对象
   * @return
   */
  @PostMapping("/add")
  /*@PostMapping
  映射一个POST请求

  Spring MVC新特性 
  
 提供了对Restful风格的支持
@GetMapping,处理get请求 
@PostMapping,处理post请求 
@PutMapping,处理put请求 
@DeleteMapping,处理delete请求
*/
    
  public Student save(Student student){
    return studentService.save(student);
  }

  /**
   * 修改学生
   * @param student
   */
  @PostMapping("/update")
  public Student update(Student student){
    return studentService.save(student);
  }

  /**
   * 删除学生
   * @param id  要删除学生id
   * @return
   */
  @GetMapping("/del/{id}")
  public String del(@PathVariable int id){
    studentService.delete(id);
    return "yes";
  }

  @GetMapping("/findByName/{name}")
  public List<Student> findByName(@PathVariable String name){
  return studentService.findStuByName(name);
  }

  @GetMapping("/query")
  public Page<Student> findByPage(Integer page , HttpServletResponse response){
    response.setHeader("Access-Control-Allow-Origin","*"); //解决跨域请求
    if(page==null||page<=0){
      page=0;
    }else{
      page-=1;
    }
    return studentService.findAll(page,5);
  }
}

@RestController

应用在Controller层的类上面,@RestController注解相当于@ResponseBody + @Controller合在一起的作用,同时返回的数据为json数据

使用@Controller 注解,在对应的方法上,视图解析器可以解析return 的jsp,html页面,并且跳转到相应页面
若返回json等内容到页面,则需要加@ResponseBody注解

@PostMapping(value = "/add")等价于@RequestMapping(value = "/add",method = RequestMethod.POST)

5.利用HBuilder进行前端编写

Jquery.js内容到https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js复制即可

主页面:index.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/stu/s/query?page='+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.age+"</td><td>"+stu.sex+"</td>"+
              "<td><a href=''>编辑</a> <a href='http://localhost:8888/stu/s/del/"+stu.id+"'>删除</a></td></tr>";
            }
            
            htmlStr += "</table>";
            
            $("#show").html(htmlStr);
          }
        });
      }
      
    </script>
    
  </head>
  <body>
    
    <h1 style="text-align: center;">学生管理系统</h1>
    <hr>
    <a href="add.html" rel="external nofollow" >添加学生</a>
    
    <div id="show">
      
    </div>
    
    <a href="javascript:upPage();" rel="external nofollow" >上一页</a>  <a href="javascript:downPage();" rel="external nofollow" >下一页</a>
    
  </body>
</html>

页面效果

添加学生的页面信息add.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <h1>添加学生</h1>
    <hr>
    <form action="http://localhost:8888/stu/s/add" method="post">
      <p>
        姓名:<input type="text" name="name" />
      </p>
      <p>
        年龄:<input type="text" name="age" />
      </p>
      <p>
        性别:
        <input type="radio" name="sex" value="男" checked />男
        <input type="radio" name="sex" value="女" />女
      </p>
      <p>
        <input type="submit" value="保存" />
      </p>
    </form>
  </body>
</html>

页面效果

'

如何利用分页

直接调用Dao接口的父类JPA接口的分页方法

在Service接口层定义:

/**
   * 分页查询所有数据
   * @param page
   * @param pageSize
   * @return
   */
  Page<Student> findAll(int page,int pageSize);

Service实现:

 public Page<Student> findAll(int page,int pageSize) {
    Pageable pageable= PageRequest.of(page,pageSize);
    return studentDao.findAll(pageable);

  }

Controller层:

@GetMapping("/query")
  public Page<Student> findByPage(Integer page , HttpServletResponse response){
    response.setHeader("Access-Control-Allow-Origin","*");
    if(page==null||page<=0){
      page=0;
    }else{
      page-=1;
    }
    return studentService.findAll(page,5);
  }

加载全部内容

相关教程
猜你喜欢
用户评论