SpringBoot+Jpa实现增删改查以及分页查询

SpringBoot+Jpa实现增删改查以及分页查询

一,项目所用得框架

1,使用工具IDEA

2,使用springboot框架+JPA+Mysql

二,项目的一个总体目录

img

1,springboot+jpa实现增删改查

​ 里面分为四部分,分别是

​ controller——->控制层

​ domain———->实体层

​ repository——->接口

​ service————>业务逻辑

三,每一层代码是如何实现的

一,domain

​ domain层中有几点很重要

​ 1,@Entity

​ 2,@Table(name=”employee”)

​ 表示根据实体类所生成的数据库中的表名

​ 3,@Id

​ 表示id为主键,

​ 4,@GeneratedValue(strategy=GenerationType.AUTO)

​ 表示是主键生成策略,如果加上了这句话,那么注意此时,id的类型一定是Integer类型的,不然程序肯定爆炸

​ 5,@Colum

​ 可写可不写,因为默认将其当做字符串

package com.sudojava.springjpa.domain;


import javax.persistence.*;

@Entity  
@Table(name = "employee")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    @Column
    private String name;
    @Column
    private String address;
    @Column
    private String photo;

   ...set和get方法,toString方法,有参和无参构造
}

二,service层

    ###  

包括xxxService:

package com.sudojava.springjpa.service;

import com.sudojava.springjpa.domain.Employee;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

public interface EmployeeService {

     Employee saveEmployee(Employee employee);

     void deleteEmployee(Integer id);

     boolean updateEmployee(Employee employee);

     Page findAll(Pageable pageable);

     Page findAllByName(String name,Pageable pageable);
}

​ 1,分别写了增删改查,和分页的方法

​ 2,增的方法:返回实体类对象,参数为实体类对象,因为将新添加的保存到对象中

​ 3,删除:根据id进行删除,所以参数为id,返回值为空

​ 4,修改:返回boolean类型,参数为实体类对象

​ 5,查找:传入参数Pageable

​ 6,根据名字进行分页查询,传入名字的参数和Pageable (String name,Pageable pageable)

包括xxxServiceimpl

package com.sudojava.springjpa.service;

import com.sudojava.springjpa.domain.Employee;
import com.sudojava.springjpa.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ResourceBundle;

@Service
public class EmployeeServiceImp implements EmployeeService {

    //注入dao,注入repository

    @Autowired
    EmployeeRepository repository;

    @Override
    public Employee saveEmployee(Employee employee) {

        return repository.save(employee);
    }

    @Override
    public void deleteEmployee(Integer id)
    {
        repository.delete(id);
    }

    @Override
    public boolean updateEmployee(Employee employee) {

         repository.delete(employee.getId());
         repository.save(employee);
         return true;
    }

    @Override
    public Page findAll(Pageable pageable) {

        return repository.findAll(pageable);
    }

    @Override
    public Page findAllByName(String name, Pageable pageable) {

        return  repository.findEmployeeByNameEquals(name,pageable);
    }
}

​ 1,对于修改的话,在service没有直接的update方法所以需要先进行,删除,然后在进行添加

三,repository

package com.sudojava.springjpa.repository;

import com.sudojava.springjpa.domain.Employee;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;

public interface EmployeeRepository extends JpaRepository {
    public Page findEmployeeByNameEquals(String name,Pageable pageable);
}

​ 在这里,可以一行代码也不写,同时也可以在里面自己定义方法,定义方法的时候,可以传入pageable参数,说明,不管进行什么操作的时候都可以进行分页

四,controller

package com.sudojava.springjpa.controller;

import com.sudojava.springjpa.domain.Employee;
import com.sudojava.springjpa.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.function.Consumer;

@Controller
public class EmployeeController {


    @Autowired
    EmployeeService service;

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ModelAndView add(Employee employee) {
        ModelAndView modelAndView = new ModelAndView();
        Employee result = service.saveEmployee(employee);
        if (result!=null){
            modelAndView.setViewName("success");
        }else{
            modelAndView.setViewName("fail");
        }
        return modelAndView;
    }

    @RequestMapping(value = "/delete/{id}",method = RequestMethod.GET)
    public String delete(@PathVariable Integer id){
        service.deleteEmployee(id);
        return "success";
    }

    @RequestMapping(value = "/find/{currentPage}",method = RequestMethod.GET)
    public String findAll(@PathVariable Integer currentPage){
        PageRequest request = new PageRequest(currentPage-1,6);
        Page page = service.findAll(request);
        page.getContent().forEach(new Consumer() {
            @Override
            public void accept(Employee employee) {
                System.out.println(employee);
            }
        });
        return "success";
    }
    @RequestMapping(value = "/findname",method = RequestMethod.POST)
    public String findByName(String name,Integer currentPage){
        PageRequest request = new PageRequest(currentPage-1,6);
        Page page = service.findAllByName(name,request);
        page.getContent().forEach(new Consumer() {
            @Override
            public void accept(Employee employee) {
                System.out.println(employee);
            }
        });
        return "success";
    }
    @RequestMapping(value = "update",method = RequestMethod.GET)
    public String update(Employee employee){
        service.updateEmployee(employee);
        return "success";
    }
}

四,配置文件

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=jing
spring.datasource.url=jdbc:mysql://localhost:3306/mysql

spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.generate-ddl=true

五,进行测试

package com.sudojava.springjpa;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration
@SpringBootTest
public class SpringjpaApplicationTest2 {

    @Autowired
    private WebApplicationContext context;

    private MockMvc mockMvc;


    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
    }

    @Test
    public void add() throws Exception {
        mockMvc.perform(
                MockMvcRequestBuilders.post("/add")
                        .characterEncoding("utf-8")
                        .contentType("text/html;charset=utf-8")
                        .param("name", "jack")
                        .param("address", "beijing")
                        .param("photo", "CCC")
        ).andDo(MockMvcResultHandlers.print());
    }

    @Test
    public void delete() throws Exception {
        mockMvc.perform(
                MockMvcRequestBuilders.get("/delete/1")
        ).andDo(MockMvcResultHandlers.print());
    }

    @Test
    public void queryAll() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/find/1"))
                .andDo(MockMvcResultHandlers.print());
    }

    @Test
    public void queryName() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.post("/findname")
                .param("name", "jack")
                .param("currentPage", 1 + "")
        )
                .andDo(MockMvcResultHandlers.print());
    }
    @Test
    public void update() throws Exception{
        mockMvc.perform(MockMvcRequestBuilders.get("/update")
            .param("id","1")
                .param("name","shabi")
                .param("address","aaaa")
                .param("photo","aaaa")
        ).andDo(MockMvcResultHandlers.print());

    }
}

1,在测试这一块用到了mock

​ mock的具体使用步骤

​ 1,@RunWith(SpringJUnit4ClassRunner.class)
​ @WebAppConfiguration
​ @ContextConfiguration
​ @SpringBootTest

​ 这四个标签必不可少,

​ 2,进行注入

​ @AutoWired

​ @Autowired

private WebApplicationContext context;

private MockMvc mockMvc;

​ 3,

@Before
public void setup() {
    mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}

​ 4,进行测试,记住顺序,先进行builder后进行handler

​ @Test

public void update() throws Exception{

    mockMvc.perform(MockMvcRequestBuilders.get("/update")
        .param("id","1")
            .param("name","shabi")
            .param("address","aaaa")
            .param("photo","aaaa")
    ).andDo(MockMvcResultHandlers.print());

}

你可能感兴趣的:(初级程序员,springboot,jpa)