CrudRepository save() to Add a New Instance
Let’s create a new instance of MerchandiseEntity and save it to the database using the 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); |
Running this will create a new entry in the database table for MerchandiseEntity. Notice that we never specified an id. The instance is initially created with a null value for its id and when we call the save() method, an id is automatically generated.
The save() method returns the saved entity, including the updated id field.
CrudRepository save() to Update an Instance
We can use the same save() method to update an existing entry in our database. Suppose we had saved a MerchandiseEntity instance with a specific title:
1
2
3
| MerchandiseEntity pants = new MerchandiseEntity( "Pair of Pants" , 34.99 ); pants = repo.save(pants); |
But later we found that we wanted to update the price of the item. We could then simply get the entity from the database, make the change and use the save() method as before.
Assuming we know the id of the item (pantsId), we can use the CRUDRepositorymethod findById to get our entity from the database:
1
2
3
| MerchandiseEntity pantsInDB = repo.findById(pantsId).get(); pantsInDB.setPrice( 44.99 ); repo.save(pantsInDB); |
Here, we’ve updated our original entity with a new price and saved the changes back to the database.
Conclusion
In this quick article, we’ve covered the use of CrudRepository‘s save() method. This method can be used to add a new entry into your database as well as updating an existing one.
No comments:
Post a Comment