SpringBoot入门二:CURD增删改查

SpringBoot实现增删改查
系统环境:
编辑器:Idea2018.1
操作系统:win7
maven:1.8.0_171

步骤简介:

  1. pom引入依赖
  2. application.properties加上数据库配置
  3. 创建students表
  4. 创建文件目录结构
  5. 填入业务代码

步骤

一、pom引入依赖

在pom中添加mysql和jpa的依赖,打开pom文件,找到dependencies节点,内部加上如下代码:

	<dependencies>
		<!--spring-boot-starter-web、spring-boot-starter-test 依赖略-->
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

二、application.properties加上数据库配置

打开application.properties,加入mysql的配置

spring.datasource.url=jdbc:mysql://localhost/test?characterEncoding=UTF8&characterSetResults=UTF8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
# 打印sql和参数
spring.jpa.show-sql=true
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=trace

加characterXXX配置原因参考:
Java操作Mysql时为什么加characterXXX
加serverTimezone原因可以参考:
DataSource中加serverTimezone原因
The server time zone value XXX报错解决

三、创建students表

表结构只包含自增主键id、非空字符列name

CREATE TABLE `students` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=27 DEFAULT CHARSET=utf8

四、创建文件目录结构

在com.example.demo下创建目录:controller、entity、repository、service
各目录作用:
controller中添加负责路由
entity负责数据库Dao映射
repository

五、填入代码

  1. Entity
package com.example.demo.entity;

import javax.persistence.*;

@Entity
@Table(name = "students")
public class StudentEntity{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;

    public StudentEntity() {
    }

    public StudentEntity(String name) {
        this.name = name;
    }
    public StudentEntity(StudentRequestEntity studentRequestEntity) {
        this.name = studentRequestEntity.getName();
    }

    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;
    }
}
package com.example.demo.entity;

public class StudentRequestEntity{
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
  1. Repository
package com.example.demo.repository;

import com.example.demo.entity.StudentEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface StudentRepository extends JpaRepository<StudentEntity, Integer> {

}
  1. Service
package com.example.demo.service;

import com.example.demo.entity.StudentEntity;
import com.example.demo.entity.StudentRequestEntity;
import com.example.demo.repository.StudentRepository;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class StudentService{
    private StudentRepository studentRepository;

    /**
     * 有人在这加了@Autowired注解,我试了下,不加也可以
     * @param studentRepository
     */
    public StudentService(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    public Optional<StudentEntity> findOne(int id){
        StudentEntity studentEntity = new StudentEntity();
        studentEntity.setId(id);
        return studentRepository.findOne(Example.of(studentEntity));
    }

    public Optional<StudentEntity> findById(int id){
        return studentRepository.findById(id);
    }

    public List<StudentEntity> findAll(){
        return studentRepository.findAll();
    }

    public StudentEntity save(StudentRequestEntity studentRequestEntity){
        StudentEntity studentEntity = Optional.of(studentRequestEntity).map(StudentEntity::new).get();
        return studentRepository.save(studentEntity);
    }

    public StudentEntity save(String name, int id){
        Optional<StudentEntity> optionalStudentEntity = studentRepository.findById(id);
        if(optionalStudentEntity.isPresent()) {
            StudentEntity studentEntity = optionalStudentEntity.get();
            studentEntity.setName(name);
            return studentRepository.save(studentEntity);
        }
        return null;
    }

    public void delete(int id){
        studentRepository.deleteById(id);
    }
}
  1. Controller
package com.example.demo.controller;

import com.example.demo.entity.StudentEntity;
import com.example.demo.entity.StudentRequestEntity;
import com.example.demo.service.StudentService;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * 学生类,用来测试数据库的增删改查
 */
@RestController
public class StudentController {
    private StudentService studentService;

    public StudentController(StudentService studentService) {
        this.studentService = studentService;
    }

    /**
     * 根据id查询单条
     * @param id int
     * @return
     */
    @RequestMapping(value = "/student/{id}", method = RequestMethod.GET)
    public Optional<StudentEntity> findById(@PathVariable int id) {
        return studentService.findById(id);
    }

    /**
     * 根据id查询单条
     * @param id int
     * @return
     */
    @RequestMapping(value = "/student/one", method = RequestMethod.GET)
    public Optional<StudentEntity> findOne(@RequestParam int id){
        return studentService.findOne(id);
    }

    /**
     * 查询所有
     * @return
     */
    @RequestMapping(value = "/student", method = RequestMethod.GET)
    public List<StudentEntity> findAll(){
        return studentService.findAll();
    }

    /**
     * 插入一条
     * @param studentRequestEntity
     * @return
     */
    @RequestMapping(value = "/student", method = RequestMethod.POST)
    public StudentEntity save(@RequestBody StudentRequestEntity studentRequestEntity){
        return studentService.save(studentRequestEntity);
    }

    /**
     * 根据id删除一条
     * @param id
     */
    @RequestMapping(value = "/student/{id}", method = RequestMethod.DELETE)
    public void delete(@PathVariable int id){
        studentService.delete(id);
    }

    /**
     * 根据id修改一条
     * @param name
     * @param id
     * @return
     */
    @RequestMapping(value = "/student/{id}", method = RequestMethod.PUT)
    public StudentEntity save(@RequestParam String name, @PathVariable int id){
        return studentService.save(name, id);
    }

    /**
     * 根据id修改一条
     * @param name
     * @param id
     * @return
     */
    @RequestMapping(value = "/student/one/{id}", method = RequestMethod.PUT)
    public StudentEntity saveOne(@RequestBody String name, @PathVariable int id){
        return studentService.save(name, id);
    }
}

六、运行代码,测试Restful接口

结果:略

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值