1.新建项目
开发工具使用IDEA,数据库用MYSQL5.7,Maven3.5.3导入依赖jar,JDK1.8版本.
mysql
mysql-connector-java
5.1.38
3.配置druid数据库连接池
com.alibaba
druid
1.1.10
#数据源配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/student?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=/jixian
#配置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
4.先写一个控制层测试环境是否搭建成功
建一个controller包
代码如下:
package com.jixian.test.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class StudentController {
@RequestMapping("/hello")
public void hello(){
System.out.println("hello");
}
}
打开浏览器在地址栏输入
看到控制台输出hello,环境就搭建成功了。
1.建表
创建一个t_stu表,id为主键。
2.写实体
分为如下几层:
定义一个Students实体类:
在实体类上用@Entity注解来表明实体.
@Table(name = “t_stu”)映射数据库表,name为数据库的表名。
@Id注解定义主键
@GeneratedValue(strategy = GenerationType.IDENTITY)定义主键自增
package com.kude.demo.entity;
import javax.persistence.*;
@Entity
@Table(name = "t_stu")
public class Students {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String sex;
private int age;
private String username;
private String 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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Students(int id, String name, String sex, int age, String username, String password) {
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
this.username = username;
this.password = password;
}
public Students() {
}
@Override
public String toString() {
return "Students{" +
"id=" + id +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
3.定义Dao接口继承JpaRepository:
JpaRepository接口有简单的增删改查方法,通过继承可以使用相应的方法
public interface StudentDao extends JpaRepository {
Students findStuById(int id);
@Query(name = "findByName",nativeQuery = true,value =
"select * from t_stu where name = :name")
List findByName(@Param("name")String name);
}
@Query注解用来自定义SQL语句,name是方法名,nativeQuery = true时,可以执行原生sql语句,所谓原生sql,也就是说这段sql拷贝到数据库中,然后把参数值给一下就能运行了。
value是自定义的SQL语句。
@Param用来参数绑定
4.定义Service接口并实现:
StudentService接口代码如下:
package com.kude.demo.service;
import com.kude.demo.entity.Students;
import org.springframework.data.domain.Page;
import java.util.List;
public interface StudentService {
Students findById(int id);
void delete(int id);
Students save(Students students);
Page findAll(int page,int pagesize);
Students update(Students students);
List findStuByName(String name);
}
StudentServiceImpl来实现代码如下:
package com.kude.demo.service;
import com.kude.demo.dao.StudentDao;
import com.kude.demo.entity.Students;
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.stereotype.Service;
import java.util.List;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao studentDao;
@Override
public Students findById(int id) {
return studentDao.findStuById(id);
}
@Override
public void delete(int id) {
studentDao.deleteById(id);
}
@Override
public Students save(Students students) {
return studentDao.save(students);
}
@Override
public Page findAll(int page, int pagesize) {
Pageable pageable = PageRequest.of(page,pagesize);
return studentDao.findAll(pageable);
}
public List findAll(){
return studentDao.findAll();
}
@Override
public Students update(Students students) {
return studentDao.save(students);
}
@Override
public List findStuByName(String name) {
return studentDao.findByName(name);
}
}
@Service定义Service层,StudentServiceImpl用@Service
@Autowired自动为属性赋值
@Autowired
private StudentDao studentDao;
5.定义StudentController控制层:
@RestController标注controller控制层
@RestController注解,相当于@Controller+@ResponseBody两个注解的结合,返回json数据不需要在方法前面加@ResponseBody注解了,但使用@RestController这个注解,就不能返回jsp,html页面,视图解析器无法解析jsp,html页面。
@ResponseBody 表示该方法的返回结果直接写入 HTTP response body 中,一般在异步获取数据时使用【也就是AJAX】,在使用 @RequestMapping后,返回值通常解析为跳转路径,但是加上 @ResponseBody 后返回结果不会被解析为跳转路径,而是直接写入 HTTP response body 中。 比如异步获取 json 数据,加上 @ResponseBody 后,会直接返回 json 数据。@RequestBody 将 HTTP 请求正文插入方法中,使用适合的 HttpMessageConverter 将请求体写入某个对象。
@RequestMapping标注请求映射的路径
value是路径名,method 是请求方式get/post
@PostMapping注解是Post请求映射
@GetMapping为Get请求映射
package com.kude.demo.controller;
import com.kude.demo.entity.Students;
import com.kude.demo.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
@RequestMapping("/stu")
public class StudentController {
@Autowired
private StudentService studentService;
@PostMapping("/reg")
public Students reg(Students students){
return studentService.save(students);
}
@GetMapping("/findAll")
public Page findAll(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);
}
@GetMapping("/delete/{id}")
public String delete(@PathVariable int id){
studentService.delete(id);
return "sucesss";
}
/**
*
* @param students
* @return
*/
@PostMapping("/update")
public Students update(Students students){
return studentService.save(students);
}
@GetMapping("/select/{id}")
public Students select(@PathVariable int id)throws Exception{
return studentService.findById(id);
}
@GetMapping("/findByName/{name}")
public List findByName(@PathVariable String name){
return studentService.findStuByName(name);
}
}
在默认的情况下,Spring会对@PathVariable注解的变量进行自动赋值.
前端页面:
index.html:
学生管理系统
添加学生
上一页 下一页
add.html
添加学生
(一)数据的分页
直接调用Dao接口的父类JPA接口的分页方法
1.在Service接口层定义:
Page findAll(int page, int pagesize);
2.Service实现:
public Page findAll(int page, int pagesize) {
Pageable pageable = PageRequest.of(page,pagesize);
return studentDao.findAll(pageable);
}
3.Controller层:
@GetMapping("/findAll")
public Page findAll(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);
}
(二)解决跨域请求
response.setHeader("Access-Control-Allow-Origin","*");