Springデータ - CrudRepository save()メソッド

Spring Data – CrudRepository save()メソッド

1. 概要

CrudRepositorySpring Data interface for generic CRUD operations on a repository of a specific type.です。データベースと対話するためのいくつかのメソッドをすぐに使用できます。

このチュートリアルでは、CrudRepositorysave()メソッドをいつどのように使用するかを説明します。

Spring Dataリポジトリの詳細については、CrudRepositoryをフレームワークの他のリポジトリインターフェイスと比較するarticleをご覧ください。

参考文献:

Spring Data JPA @Query

Spring Data JPAで@Queryアノテーションを使用して、JPQLとネイティブSQLを使用してカスタムクエリを定義する方法を学びます。

Spring Data JPA-派生削除メソッド

Spring DataのdeleteByおよびremoveByメソッドを定義する方法を学ぶ

2. 依存関係

Spring DataおよびH2データベースの依存関係をpom.xmlファイルに追加する必要があります。


    org.springframework.boot
    spring-boot-starter-data-jpa


    com.h2database
    h2
    runtime

3. 応用例

まず、MerchandiseEntityというSpringDataエンティティを作成しましょう。 このクラスはdefine the data types that will get persisted to the database when we call the save()メソッドになります:

@Entity
public class MerchandiseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private double price;

    private String brand;

    public MerchandiseEntity() {
    }

    public MerchandiseEntity(String brand, double price) {
        this.brand = brand;
        this.price = price;
    }
}

次に、MerchandiseEntityを操作するためのCrudRepositoryインターフェイスを作成しましょう。

@Repository
public interface InventoryRepository
  extends CrudRepository {
}

Here we specify the entity’s class and the entity id’s class, MerchandiseEntity and Long。 このリポジトリのインスタンスがインスタンス化されると、MerchandiseEntityクラスを操作するための基盤となるロジックが自動的に配置されます。

したがって、コードが非常に少ないので、save()メソッドの使用を開始する準備ができています。

4. 新しいインスタンスを追加するためのCrudRepository save()

MerchandiseEntityの新しいインスタンスを作成し、InventoryRepositoryを使用してデータベースに保存しましょう。

InventoryRepository repo = context
  .getBean(InventoryRepository.class);

MerchandiseEntity pants = new MerchandiseEntity(
  "Pair of Pants", BigDecimal.ONE);
pants = repo.save(pants);

これを実行すると、データベーステーブルにMerchandiseEntityの新しいエントリが作成されます。 idを指定したことがないことに注意してください。 インスタンスは、最初はそのidnull値で作成され、save()メソッドを呼び出すと、idが自動的に生成されます。

save()メソッドは、更新されたidフィールドを含む保存されたエンティティを返します。

5. インスタンスを更新するためのCrudRepository save()

同じsave()メソッドto update an existing entry in our databaseを使用できます。 特定のタイトルでMerchandiseEntityインスタンスを保存したとします。

MerchandiseEntity pants = new MerchandiseEntity(
  "Pair of Pants", 34.99);
pants = repo.save(pants);

しかし、後で、アイテムの価格を更新したいことがわかりました。 次に、データベースからエンティティを取得し、変更を加えて、前と同じようにsave()メソッドを使用するだけです。

アイテムのidpantsId)がわかっているとすると、CRUDRepositoryメソッドfindByIdを使用して、データベースからエンティティを取得できます。

MerchandiseEntity pantsInDB = repo.findById(pantsId).get();
pantsInDB.setPrice(44.99);
repo.save(pantsInDB);

ここでは、元のエンティティを新しい価格で更新し、変更をデータベースに保存しました。

6. 結論

この簡単な記事では、CrudRepositoryのsave()メソッドの使用について説明しました。 このメソッドを使用して、データベースに新しいエントリを追加したり、既存のエントリを更新したりできます。

いつものように、記事のコードはover on GitHubです。