Spring Data – CrudRepository save() Method
1.概述
CrudRepository是一个Spring Data接口,用于在特定类型的存储库上进行通用CRUD操作。它提供了几种现成的与数据库交互的方法。
在本教程中,我们将说明如何以及何时使用CrudRepository save()方法。
要了解有关Spring Data存储库的更多信息,请查看我们的文章,该文章将CrudRepository与框架的其他存储库接口进行了比较。
进一步阅读:
Spring Data JPA @查询
Spring Data JPA –派生的删除方法
2.依存关系
我们必须将Spring Data和H2数据库依赖项添加到我们的pom.xml文件中:
1 2 3 4 5 6 7 8 9 | <dependency> <groupId>org.springframework.boot</groupId> spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> h2</artifactId> <scope>runtime</scope> </dependency> |
3.示例应用
首先创建一个名为MerchandiseEntity的Spring Data实体。此类将定义当我们调用save()方法时将持久化到数据库的数据类型:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
接下来,让我们创建一个CrudRepository接口以使用MerchandiseEntity:
1 2 3 4 | @Repository public interface InventoryRepository extends CrudRepository<MerchandiseEntity, Long> { } |
在这里,我们指定实体的类别和实体ID的类别MerchandiseEntity和Long。当实例化此存储库的实例时,将自动使用基础逻辑来处理我们的MerchandiseEntity类。
因此,只需很少的代码,我们就可以开始使用save()方法了。
4. CrudRepository save()添加新实例
让我们创建一个MerchandiseEntity的新实例,并使用InventoryRepository将其保存到数据库中:
1 2 3 4 5 6 | InventoryRepository repo = context .getBean(InventoryRepository.class); MerchandiseEntity pants = new MerchandiseEntity( "Pair of Pants", BigDecimal.ONE); pants = repo.save(pants); |
运行此命令将在数据库表中为MerchandiseEntity创建一个新条目。请注意,我们从未指定ID。实例最初是用ID的null值创建的,当我们调用save()方法时,会自动生成一个ID。
save()方法返回保存的实体,包括更新的id字段。
5. CrudRepository save()更新实例
我们可以使用相同的save()方法来更新数据库中的现有条目。假设我们保存了一个具有特定标题的MerchandiseEntity实例:
1 2 3 | MerchandiseEntity pants = new MerchandiseEntity( "Pair of Pants", 34.99); pants = repo.save(pants); |
但是后来我们发现我们想更新商品的价格。然后,我们可以简单地从数据库中获取实体,进行更改并像以前一样使用save()方法。
假设我们知道商品的ID(pantsId),则可以使用CRUDRepository方法findById从数据库中获取我们的实体:
1 2 3 | MerchandiseEntity pantsInDB = repo.findById(pantsId).get(); pantsInDB.setPrice(44.99); repo.save(pantsInDB); |
在这里,我们用新价格更新了原始实体,并将更改保存回数据库中。
六,结论
在这篇快速文章中,我们介绍了CrudRepository的ssave()方法的使用。此方法可用于向数据库中添加新条目以及更新现有条目。
像往常一样,本文的代码在GitHub上结束。