首页 > 数据库技术 > 详细

springboot(2) 数据库操作

时间:2020-03-01 22:56:41      阅读:99      评论:0      收藏:0      [点我收藏+]

一。 JPA

1.pom文件引入jpa和mysql依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

2.application.yml文件增加数据库配置

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8
    username: root
    password: root
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

3.与表girl对应的实体类

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Girl {
    @Id
    @GeneratedValue
    private Integer id;
    private String cupSize;
    private String age;

4.新建数据库操作respository

public interface GirlRespository extends JpaRepository<Girl, Integer> {
    public Girl findByAge(String age);
}

5.controller层操作数据库

@RestController
public class GirlController {
    @Autowired
    private GirlRespository girlRespository;
    
    @Autowired
    private GirlService girlService;
    
    @RequestMapping(value = "/girls", method = RequestMethod.GET)
    public List<Girl> getList(){
        return girlRespository.findAll();
    }
    @PostMapping(value = "/girls/insertTwo")
    public void insertTwo() {
        girlService.insertTwo();
    }
    @RequestMapping(value = "/girls", method = RequestMethod.POST)
    public void addOne(@RequestParam(value = "cupSize")String cupSize,
            @RequestParam(value = "age")String age){
        Girl girl = new Girl();
        girl.setAge(age);
        girl.setCupSize(cupSize);
        girlRespository.save(girl);
    }
    
    @GetMapping(value = "/girls/{id}")
    public Girl getOne(@PathVariable(value = "id")Integer id) {
        return girlRespository.getOne(id);
    }
    
    @PutMapping(value = "/girls/{id}")
    public Girl updateOne(@PathVariable(value = "id")Integer id,@RequestParam(value = "cupSize")String cupSize,
            @RequestParam(value = "age")String age) {
        Girl girl = new Girl();
        girl.setId(id);
        girl.setAge(age);
        girl.setCupSize(cupSize);
        return girlRespository.save(girl);
    }
    
    @DeleteMapping(value = "/girls/{id}")
    public void delOne(@PathVariable(value = "id")Integer id) {
        girlRespository.deleteById(id);
    }
    
    @GetMapping(value = "/girls/age/{age}")
    public Girl getOne(@PathVariable(value = "age")String age) {
        return girlRespository.findByAge(age);
    }
}

6.数据库事务操作,只需在方法上使用标签@Transactional

springboot(2) 数据库操作

原文:https://www.cnblogs.com/t96fxi/p/12392547.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!