JPA实现简单的增删改查功能

JPA实现简单的增删改查功能
-----------------------------------------model类---------------------------------------------------

package com.dfl.ycp3.stock.common.model;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Date;

/**
 * @author fyq
 * @time 2019/12/03
 * @Description 学生实体类
 */
@Entity
@Table(name = "student")
@Data
public class Student implements Serializable {
     

    private static final long serialVersionUID = -2333472778385823832L;
    
    //学号
    @Id
    @Column(name = "studentnumber")
    private String studentNumber;

	//姓名
    @Column(name = "studentname")
    private String studentName;

	//性别
    @Column(name = "studentsex")
    private String studentSex;

	//出生日期
    @Column(name = "studentbirthday")
    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
    private Date studentBirthday;

	//年龄
    @Column(name = "studentage")
    private Integer studentAge;

	//爱好
    @Column(name = "studenthobby")
    private String studentHobby;

	//创建时间
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "createtime")
    private Date createTime;

	//创建人
    @Column(name = "creator")
    private String creator;

	//更新时间
    @Column(name = "updatetime")
    private Date updateTime;

	//更新人
    @Column(name = "updateperson")
    private String updatePerson;

    public Student() {
     
    }

    public Student(String studentNumber, String studentName, String studentSex, Date studentBirthday, Integer studentAge,
                   String studentHobby, Date createTime, String creator, Date updateTime, String updatePerson) {
     
        this.studentNumber = studentNumber;
        this.studentName = studentName;
        this.studentSex = studentSex;
        this.studentBirthday = studentBirthday;
        this.studentAge = studentAge;
        this.studentHobby = studentHobby;
        this.createTime = createTime;
        this.creator = creator;
        this.updateTime = updateTime;
        this.updatePerson = updatePerson;
    }

    public String getStudentNumber() {
     
        return studentNumber;
    }

    public void setStudentNumber(String studentNumber) {
     
        this.studentNumber = studentNumber;
    }

    public String getStudentName() {
     
        return studentName;
    }

    public void setStudentName(String studentName) {
     
        this.studentName = studentName;
    }

    public String getStudentSex() {
     
        return studentSex;
    }

    public void setStudentSex(String studentSex) {
     
        this.studentSex = studentSex;
    }

    public Date getStudentBirthday() {
     
        return studentBirthday;
    }

    public void setStudentBirthday(Date studentBirthday) {
     
        this.studentBirthday = studentBirthday;
    }

    public Integer getStudentAge() {
     
        return studentAge;
    }

    public void setStudentAge(Integer studentAge) {
     
        this.studentAge = studentAge;
    }

    public String getStudentHobby() {
     
        return studentHobby;
    }

    public void setStudentHobby(String studentHobby) {
     
        this.studentHobby = studentHobby;
    }

    public Date getCreateTime() {
     
        return createTime;
    }

    public void setCreateTime(Date createTime) {
     
        this.createTime = createTime;
    }

    public String getCreator() {
     
        return creator;
    }

    public void setCreator(String creator) {
     
        this.creator = creator;
    }

    public Date getUpdateTime() {
     
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
     
        this.updateTime = updateTime;
    }

    public String getUpdatePerson() {
     
        return updatePerson;
    }

    public void setUpdatePerson(String updatePerson) {
     
        this.updatePerson = updatePerson;
    }

}

-----------------------------------------Dao层---------------------------------------------------

package com.dfl.ycp3.stock.repository;

import com.dfl.ycp3.stock.common.model.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Repository
public interface StudentDao extends JpaRepository<Student,Integer>, JpaSpecificationExecutor<Student> {
     

    //查询全部
    @Query(value = "SELECT s FROM Student s order by s.studentNumber")
    List<Student> findAll();

    //按学号查询
    @Query(value = "SELECT s FROM Student s WHERE s.studentNumber in(?1)")
    Student findByStudentNumber(String  studentNumber);

    //按学号修改
    @Modifying
    @Transactional
    @Query(value = "update Student set studentName= :studentName ,studentSex= :studentSex ,studentBirthday= :studentBirthday ," +
            "studentAge= :studentAge ,studentHobby= :studentHobby ,createTime= :createTime ,creator= :creator ," +
            "updateTime= :updateTime ,updatePerson= :updatePerson  where studentNumber = :studentNumber")
    void updateByStudentNumber(
    					  @Param("studentName")String studentName, @Param("studentSex")String studentSex,
                          @Param("studentBirthday") Date studentBirthday, @Param("studentAge")Integer studentAge,
                          @Param("studentHobby")String studentHobby, @Param("createTime")Date createTime,
                          @Param("creator")String creator, @Param("updateTime")Date updateTime,
                          @Param("updatePerson")String updatePerson,@Param("studentNumber")String studentNumber);

    //按学号删除
    @Modifying
    @Transactional
    @Query(value = "delete from Student where studentNumber= :studentNumber ")
    void deleteByStudentNumber(String studentNumber);


}

注意:
1、查询语句中的“Student”是实体类的名字,不是数据库的名字
2、修改和删除的返回值类型只有void,int和Integer三种
3、@Modifying需要和@Transactional配合使用才能正常使用。
@Modifying的作用是声明执行的sql语句是修改(修改或删除)操作,@Transactional的作用是提供事务支持,当@Query发生错误时,会回滚到执行前的状态

-----------------------------------------Controller---------------------------------------------------

package com.dfl.ycp3.stock.controller.api;

import com.dfl.ycp3.common.utils.DateUtil;
import com.dfl.ycp3.stock.common.model.Student;
import com.dfl.ycp3.stock.repository.StudentDao;
import com.wordnik.swagger.annotations.ApiParam;
import com.yichengpai.common.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Api(description = "学生信息")
@RestController
@RequestMapping(value = "/student")
public class StudentController {
     
    @Autowired
    private StudentDao studentDao;
    private static final Logger logger= LoggerFactory.getLogger(StudentController.class);

    @ApiOperation(value = "查询学生信息",httpMethod = "GET")
    @RequestMapping(value = "/findAll",method = RequestMethod.GET)
    public List<Student> findAll(){
     
        List<Student> list = studentDao.findAll();
        return list;
    }


    @ApiOperation(value = "按学号查询学生信息",httpMethod = "GET")
    @RequestMapping(value = "/findByStudentNumber",method = RequestMethod.GET)
    public Result findByStudentNumber(
            @RequestParam(value = "studentNumber",required = true) String studentNumber
    ){
     
        Student student = studentDao.findByStudentNumber(studentNumber);
        if (student == null){
     
            return Result.fail("fail", "该学号不存在,无法查询!");
        }
        return Result.success(student);
    }


    @ApiOperation(value = "添加学生信息",httpMethod = "POST")
    @RequestMapping(value = "/addStudent",method = RequestMethod.POST)
    public Result addStudent(
            @ApiParam("学号(唯一,不可重复)") @RequestParam(value = "studentNumber", required = true) String studentNumber,
            @ApiParam("姓名") @RequestParam(value = "studentName", required = true) String studentName,
            @ApiParam("性别") @RequestParam(value = "studentSex", required = false) String studentSex,
            @ApiParam("出生日期") @RequestParam(value = "studentBirthday", required = false) String studentBirthday,
            @ApiParam("年龄") @RequestParam(value = "studentAge", required = false) Integer studentAge,
            @ApiParam("爱好") @RequestParam(value = "studentHobby", required = false) String studentHobby,
            @ApiParam("创建时间") @RequestParam(value = "createTime", required = false) String createTime,
            @ApiParam("创建人") @RequestParam(value = "creator", required = false) String creator,
            @ApiParam("更新时间") @RequestParam(value = "updateTime", required = false) String updateTime,
            @ApiParam("更新人") @RequestParam(value = "updatePerson", required = false) String updatePerson
    ) {
     
        Date birthday = DateUtil.parseStringToDate(studentBirthday,"yyyy-MM-dd");
        Date ctime = DateUtil.parseStringToDate(createTime+" 00:00:00","yyyy-MM-dd HH:mm:ss");
        Date utime = DateUtil.parseStringToDate(updateTime+" 00:00:00","yyyy-MM-dd HH:mm:ss");
        Student student = studentDao.findByStudentNumber(studentNumber);
        if(student !=null){
     
            return Result.fail("fail", "该学号已经存在,不可重复添加!");
        }else {
     
            studentDao.save(new Student(studentNumber, studentName, studentSex, birthday, studentAge, studentHobby, ctime, creator, utime, updatePerson));
            return Result.success("");
        }
    }


    @ApiOperation(value = "按学号修改学生信息",httpMethod = "POST")
    @RequestMapping(value = "/updateByStudentNumber",method = RequestMethod.POST)
    public Result updateByStudentNumber(
            @ApiParam("学号(唯一,不可重复)") @RequestParam(value = "studentNumber", required = true) String studentNumber,
            @ApiParam("姓名") @RequestParam(value = "studentName", required = false) String studentName,
            @ApiParam("性别") @RequestParam(value = "studentSex", required = false) String studentSex,
            @ApiParam("出生日期") @RequestParam(value = "studentBirthday", required = false) String birthday,
            @ApiParam("年龄") @RequestParam(value = "studentAge", required = false) Integer studentAge,
            @ApiParam("爱好") @RequestParam(value = "studentHobby", required = false) String studentHobby,
            @ApiParam("创建时间") @RequestParam(value = "createTime", required = false) String ctime,
            @ApiParam("创建人") @RequestParam(value = "creator", required = false) String creator,
            @ApiParam("更新时间") @RequestParam(value = "updateTime", required = false) String utime,
            @ApiParam("更新人") @RequestParam(value = "updatePerson", required = false) String updatePerson
    ) {
     
        Date studentBirthday = DateUtil.parseStringToDate(birthday,"yyyy-MM-dd");
        Date createTime = DateUtil.parseStringToDate(ctime+" 00:00:00","yyyy-MM-dd HH:mm:ss");
        Date updateTime = DateUtil.parseStringToDate(utime+" 00:00:00","yyyy-MM-dd HH:mm:ss");
        Student student = studentDao.findByStudentNumber(studentNumber);
        if (student != null){
     
            studentDao.updateByStudentNumber(studentName,studentSex,studentBirthday,studentAge,studentHobby,
                    createTime,creator,updateTime,updatePerson,studentNumber);
            return Result.success("");
        }else{
     
            return Result.fail("fail", "该学号不存在,无法修改!");
        }

    }


    @ApiOperation(value = "按学号删除学生信息",httpMethod = "POST")
    @RequestMapping(value = "/deleteByStudentNumber",method = RequestMethod.POST)
    public Result deleteByStudentNumber(
            @ApiParam("按学号删除") @RequestParam(value = "studentNumber", required = true) String studentNumber

    ) {
     
        Student student = studentDao.findByStudentNumber(studentNumber);
        if (student !=null){
     
            studentDao.deleteByStudentNumber(studentNumber);
            return Result.success("");
        }else{
     
            return Result.fail("fail", "该学号不存在,无法删除!");
        }
    }
    
}

你可能感兴趣的:(JPA实现增删改查功能)