よわよわエンジニアの学習記録

エンジニアになってからの学びを残しておきます。間違い等ございましたら、指摘していただけると泣いて喜びます!笑

@PutMappingの使い方と使用例 Spring

@PutMappingとは?

リクエストに対してデータの更新を行う際に付与するアノテーションです。

(RequestMappingなどと同様にコントローラーのメソッドに付与します。)

 

使い方は単純なので使用例を紹介します。

 

使用例

①コントローラー(Putに関してはここのみ確認でOKです!)

package com.hourse.example.hourselist;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RaceController {
    @Autowired
    private RaceRepository raceRepository;
    
    @PutMapping("/hourse/{order_of_arrival}")
    public void racePut(@PathVariable int order_of_arrival,
            @RequestBody Tennosho tennosho) {
        tennosho.setOrder_of_arrival(order_of_arrival);
        raceRepository.save(tennosho);
    }
}

 

リポジトリ

package com.hourse.example.hourselist;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface RaceRepository extends JpaRepository<Tennosho, Integer>{

}

➂Bean

package com.hourse.example.hourselist;

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

@Entity
public class Tennosho {
    @Id
    int order_of_arrival;
    String hourse_name;
    
    
    public int getOrder_of_arrival() {
        return order_of_arrival;
    }
    public void setOrder_of_arrival(int order_of_arrival) {
        this.order_of_arrival = order_of_arrival;
    }
    public String getHourse_name() {
        return hourse_name;
    }
    public void setHourse_name(String hourse_name) {
        this.hourse_name = hourse_name;
    }
    
    
}

④application.properties

spring.jpa.show-sql = true
spring.h2.console.enabled = true
spring.datasource.url = jdbc:h2:mem:testdb
spring.jpa.defer-datasource-initialization = true

 

・実行前DB

・実行画面 200番成功! (POSTMANを使用しています)

URL:localhost:8080/hourse/1

・実行後DB 

ちゃんと変わってます!

 

所感

使い方はPOSTとほとんど同じなので、それほど難易度は高くないと思います!