zoukankan      html  css  js  c++  java
  • [Spring Boot] Adding JPA and Spring Data JPA

    JPA is just like a helper class for providing data for Controller, has method like 'findOne', 'findAll', 'saveAndFlush', 'delete'.

    in repository/ShipwreckRespository.java:

    package hello.respository;
    
    import org.springframework.data.jpa.repository.JpaRepository;
    import hello.model.Shipwreck;
    
    public class ShipwreckRespository extends JpaRepository<Shipwreck, Long>{
    
    }

    in model/Shipwreck.java:

    package hello.model;
    
    import javax.persistence.Entity;
    import javax.persistence.GenerationType;
    import javax.persistence.GeneratedValue;
    
    @Entity
    public class Shipwreck {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        Long id;
        String name;
        String description;
        String condition;
        Integer depth;
        Double latitude;
        Double longitude;
        Integer yearDiscovered;

    controller: 

    @RestController
    @RequestMapping("api/v1/")
    public class ShipController {
    
        @Autowired
        private ShipwreckRespository shipwreckRespository;
    
        @RequestMapping(value="shipwrecks", method= RequestMethod.GET)
        public List <Shipwreck>list() {
            return shipwreckRespository.findAll();
        }
    
        @RequestMapping(value = "shipwrecks", method = RequestMethod.POST)
        public Shipwreck create(@RequestBody Shipwreck shipwreck) {
            return shipwreckRespository.saveAndFlush(shipwreck);
        }
    
        @RequestMapping(value="shipwrecks/{id}", method = RequestMethod.GET)
        public Shipwreck get(@PathVariable long id) {
            return shipwreckRespository.findOne(id);
        }
    
        @RequestMapping(value="shipwrecks/{id}", method = RequestMethod.PUT)
        public Shipwreck update(@PathVariable long id, @RequestBody Shipwreck shipwreck) {
            Shipwreck shipwreckExisting = shipwreckRespository.findOne(id);
            BeanUtil.copyProperties(shipwreck, shipwreckExisting);
            return shipwreckRespository.saveAndFlush(shipwreckExisting);
        }
    
        @RequestMapping(value="shipwrecks/{id}", method = RequestMethod.DELETE)
        public Shipwreck delete(@PathVariable long id) {
    
            Shipwreck shipwreckExisting = shipwreckRespository.findOne(id);
            shipwreckRespository.delete(shipwreckExisting);
            return shipwreckExisting;
        }
    }
  • 相关阅读:
    大型运输行业实战_day03_1_基于intellij idea的非maven spring+springMVC+mybatis搭建
    大型运输行业实战_day02_2_数据模型建立
    大型运输行业实战_day02_1_数据库设计与powerDesigner使用
    MySQL 并发控制(锁得使用)
    Oracle 日期减年数、两日期相减
    Oracle 递归拼接字段
    设计模式之适配器模式(结构型)
    设计模式之桥接模式(结构型)
    设计模式之装饰模式(结构型)
    Redis学习笔记之位图
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10279329.html
Copyright © 2011-2022 走看看