LoginSignup
2
2

More than 5 years have passed since last update.

SpringBootでDB操作

Posted at

内容

検証用テーブルを作成して、SpringBootでINSERTとDELETE操作をしてみるというもの。

INSERT

INSERTの場合は、JpaRepositoryのsave()メソッドを用います。

※ちなみにUPDATEも、このsave()メソッドを使います。

HTTPリクエストしたオブジェクトをServiceクラスで少し加工して、DBに登録といった簡単なものを実装しました。

INSERTは下記パスにてリクエストを受け取るようにControllerクラスに設定しています。

/hotel/insert

Serviceクラス
@Service
@Transactional
public class HotelInsertService {

    @Autowired
    private HotelRepository hotelRepository;

    /**
     * 
     * @return
     */
    public HotelInsertResponseBody insertHotels(Hotel hotel) {
        hotel.setRegisterDatetime(new Timestamp(System.currentTimeMillis()));
        hotel.setRegisterPerson(TestUtils.API_NAME);
        Hotel res = hotelRepository.save(hotel);
        HotelInfo hotelInfo = new HotelInfo(res.getId(), res.getName(), res.getLatitude(), res.getLongitude());
        return new HotelInsertResponseBody(hotelInfo);
    }
}
HttpRequest

curlコマンドで、リクエストを投げます。

root@host:~$ curl http://localhost:8080/hotel/insert -X POST -H "Content-Type: application/json" -d "{
>   \"header\": {
>     \"uid\": \"00000\",
>     \"languageCode\": \"US\",
>     \"countryCode\": \"US\",
>     \"currencyCode\": \"USD\"
>   }, 
>   \"body\": {
>     \"id\": \"105\",
>     \"name\": \"HIJ Hotel\"
>   }
> }"
SELECT結果

先ほど登録されたid=105SELECTして、登録されているのを確認。

mysql> select * from hotel where id=105\G
*************************** 1. row ***************************
               id: 105
             name: HIJ Hotel
         latitude: NULL
        longitude: NULL
          address: NULL
     country_code: NULL
        city_code: NULL
            grade: NULL
         facility: NULL
       image_path: NULL
register_datetime: 2016-09-12 16:21:23
  register_person: test
  update_datetime: NULL
    update_person: NULL
      delete_flag: 0
  delete_datetime: NULL
    delete_person: NULL
1 row in set (0.00 sec)

DELETE

物理削除の場合は、JpaRepositoryのdelete()を用いるのですが、今回は検証しやすいようにdelete_flagを用いて論理削除する方法を取りました。

DELETEは下記パスにてリクエストを受け取るようにControllerクラスに設定しています。

/hotel/delete

Serviceクラス

HttpReqestから得たidから、findOne()メソッドを用いて対象データを取得して

そのオブジェクトのdelete_flag=1としたあとに、save()メソッドで更新するといった内容です。

@Service
@Transactional
public class HotelDeleteService {

    @Autowired
    private HotelRepository hotelRepository;

    /**
     * 
     * @return
     */
    public int deleteHotel(Hotel hotel) {
        // transform entity information as response as need
        Hotel target = hotelRepository.findOne(hotel.getId());
        target.setDeleteFlag(true);
        target.setDeleteDatetime(new Timestamp(System.currentTimeMillis()));
        target.setDeletePerson(TestUtils.API_NAME);
        hotelRepository.save(target);
        return 0;
    }
}
HttpRequest

先ほど追加した、id=105のレコードを論理削除してみます。

root@host:~$ curl http://localhost:8080/hotel/delete -X POST -H "Content-Type: application/json" -d "{
  \"header\": {
    \"uid\": \"00000\",
    \"languageCode\": \"US\",
    \"countryCode\": \"US\",
    \"currencyCode\": \"USD\"
  }, 
  \"body\": {
    \"id\": \"105\",
    \"name\": \"HIJ Hotel\"
  }
}"
SELECT結果

delete_flag=1になったことを確認することができました。

mysql> select * from hotel where id=105\G
*************************** 1. row ***************************
               id: 105
             name: HIJ Hotel
         latitude: NULL
        longitude: NULL
          address: NULL
     country_code: NULL
        city_code: NULL
            grade: NULL
         facility: NULL
       image_path: NULL
register_datetime: 2016-09-12 16:21:23
  register_person: test
  update_datetime: NULL
    update_person: NULL
      delete_flag: 1
  delete_datetime: 2016-09-12 17:15:20
    delete_person: test
1 row in set (0.00 sec)

※ちなみにEntityクラスに下記アノテーションを付与することで、論理削除を実現しています。

@Where(clause="delete_flag = 0")
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2