[Spring Boot] Adding JPA and Spring Data JPA

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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;
    }
}

 

以上是关于[Spring Boot] Adding JPA and Spring Data JPA的主要内容,如果未能解决你的问题,请参考以下文章

spring boot 系列之四:spring boot 整合JPA

Spring Boot(十五):spring boot+jpa+thymeleaf增删改查示例

spring-data-jpa 和 spring-boot-starter-data-jpa 的区别

spring boot jpa

Spring Boot 整合Spring Data JPA

Spring Boot中使用Spring Data JPA示例