Springboot和Jpa實現學生CRUD操作程式碼例項
阿新 • • 發佈:2020-03-19
前期準備
使用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,pageSize); return studentDao.findAll(pageable); }
Controller層:
@GetMapping("/query") public Page<Student> findByPage(Integer page,"*"); if(page==null||page<=0){ page=0; }else{ page-=1; } return studentService.findAll(page,5); }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。