You can modify or update the entities by defining the repository method using @Query and @Modifying annotations. All the update/delete operations are based on the transaction scope.
Step by Step Guide to update Entity using Spring Data JPA?
Now, let's see all the steps you can follow to create the project . Let's
have an example to discuss this further by having a real-world example. First,
update the pom.xml file with the following dependencies.
1. pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.0</version> <relativePath /> <!-- lookup parent from repository --> </parent> <groupId>com.codexlabs</groupId> <artifactId>spring-cloud-config-server</artifactId> <version>0.0.1-SNAPSHOT</version> <name>spring-database-server</name> <description>Demo project for Spring Boot</description> <properties> <java.version>11</java.version> <spring-cloud.version>2020.0.3</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
2. Application. Properties
Then update the application.properties file with the following h2 database properties.server.port=8080
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.datasource.url=jdbc:h2:mem:cmpe172
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password= root
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
3. Model Class
After configuring these details in the application.properties file, its time to create your first modelclass Card with the following details.
import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "CARD") public class Card { @Column(name = "id") @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Column(name = "cardNumber") private String cardNumber; @Column(name = "cardCode") private int cardCode; @Column(name = "balance") private double balance; @Column(name = "activated") private boolean activated; @Column(name = "status") private String status; public String getCardNumber() { return cardNumber; } public void setCardNumber(String cardNumber) { this.cardNumber = cardNumber; } public int getCardCode() { return cardCode; } public void setCardCode(int cardCode) { this.cardCode = cardCode; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } public boolean isActivated() { return activated; } public void setActivated(boolean activated) { this.activated = activated; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
4. Repository interface
The next step is to define the CardRepository interface. This class extends JpaRepository to get all find method which can be used for searching. We can define it as below.import org.springframework.data.jpa.repository.JpaRepository; public interface CardRepository extends JpaRepository < Card, Integer > { Card findBycardNumber(String cardNumber); Card findBycardNumberAndCardCode(String cardNumber, int cardCode);
@Transactional @Modifying @Query("update CARD c set c.balance = ?1 where c.cardNumber = ?2") int updateCardBalance(double balance, String cardNumber); @Transactional @Modifying @Query("update CARD c set c.balance = c.balance-5") int reduceCardBalanceByFive(); }
5. Testing
After that, we can test this application using Main.java, and it will help to understand how the update an entity using spring-data-jpa is going on.
Here, I didn't import the classes to the main method, and in your application,
please import those files; otherwise will not work.
on your console.
So the h2 databases records are updated with the updated queries. You can see
that from the above output. You can also see that the actual data on backend using H2 Console
That's all about how to update an entry using Spring Data JPA. It's not that difficult, and once you do a couple of examples, you can easily do this. So hope you understand how to update an entity using spring-data-jpa with the above explanation and code segments.
import java.util.Arrays; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class App { public static void main(String args[]) { SpringApplication.run(App.class, args); } public void printCards(Iterable < Card > cards, String msg) { for (Card card: cards) { System.out.println(card); } System.out.println(); } @Column(name = "cardNumber") private String cardNumber; @Column(name = "cardCode") private int cardCode; @Column(name = "balance") private double balance; @Column(name = "activated") private boolean activated; @Column(name = "status") private String status; @Bean public CommandLineRunner demo(CardRepository cardRepository) { return (args) - > { Card card1 = Card.builder() .cardNumber("1000200010") .cardCode("BE001") .balance(1200) .activated(true) .status("processing") .build(); Card card2 = Card.builder() .cardNumber("1000200011") .cardCode("BE002").balance(2300) .activated(true).status("processing").build(); Card card3 = Card.builder() .cardNumber("1000200012") .cardCode("BE002").balance(3555) .activated(true).status("processing").build(); Card card4 = Card.builder() .cardNumber("1000200013") .cardCode("BE001").balance(4945) .activated(true).status("processing").build(); Card card5 = Card.builder() .cardNumber("1000200014") .cardCode("BE001").balance(523).activated(true) .status("processing").build(); cardRepository.save(card1); cardRepository.save(card2); cardRepository.save(card3); cardRepository.save(card4); cardRepository.save(card5); List < Card > cards = cardRepository.findAll(); printCards(cards, "All the card information"); int updatedRecords = cardRepository.updateCardBalance(24000, "1000200010"); if (updatedRecords == 1) { Card card = cardRepository.findBycardNumber("1000200010").get(); printCards(Arrays.asList(card), "Card detailas with the relevant card number"); } else { System.out.println("Failed to update"); } updatedRecords = cardRepository.reduceCardBalanceByFive(); System.out.println("Total updated record : " + updatedRecords); cards = cardRepository.findAll(); printCards(cards, "All the card informations "); }; } }
6. Output
After running the above application on your local machine, the following output will be generatedon your console.
All the card information Card [id=1, cardNumber=1000200010, cardCode=BE001, balance=1200, activated=true, status=processing] Card [id=2, cardNumber=1000200011, cardCode=BE002, balance=2300, activated=true, status=processing] Card [id=3, cardNumber=1000200012, cardCode=BE002, balance=3555, activated=true, status=processing] Card [id=4, cardNumber=1000200013, cardCode=BE001, balance=4945, activated=true, status=processing] Card [id=5, cardNumber=1000200014, cardCode=BE001, balance=523, activated=true, status=processing] Card detailas with the relevant card number Card [id=1, cardNumber=1000200010, cardCode=BE001, balance=1200, activated=true, status=processing] Total updated record : 5 All the card informations Card [id=1, cardNumber=1000200010, cardCode=BE001, balance=1195, activated=true, status=processing] Card [id=2, cardNumber=1000200011, cardCode=BE002, balance=2295, activated=true, status=processing] Card [id=3, cardNumber=1000200012, cardCode=BE002, balance=3550, activated=true, status=processing] Card [id=4, cardNumber=1000200013, cardCode=BE001, balance=4940, activated=true, status=processing] Card [id=5, cardNumber=1000200014, cardCode=BE001, balance=518, activated=true, status=processing]
7. Summary
1. When building a JPQL query to alter records, we use the modifying
annotation (create, update, delete)
2. When writing a query for modification, JPQL always returns either void or
integer.
3. When writing JPQL queries, we use the
@Transactional annotation
from the
org.springframework.transaction.annotation.Transactional package.
org.springframework.transaction.annotation.Transactional package.
That's all about how to update an entry using Spring Data JPA. It's not that difficult, and once you do a couple of examples, you can easily do this. So hope you understand how to update an entity using spring-data-jpa with the above explanation and code segments.
Will see you in the next tutorial. till then you can check out our earlier
tutorials and resources as shown below.
Other Java and Spring Tutorial you may like
Thanks for reading this article so far. If you find this
Spring Data JPA Tutorial and Example, then please share it with
your friends and colleagues. If you have any questions or feedback, then
please drop a note.
P. S. - If you are a beginner and want to learn the Framework from scratch and look for some of the best online resources, you can also check out these best Spring MVC courses for beginners. This list contains free Udemy and Pluralsight courses to learn Spring MVC from scratch.
Other Java and Spring Tutorial you may like
- What is @Conditional annotation in Spring? (conditional example)
- Top 5 Frameworks Java Developer Should Know (frameworks)
- 10 Advanced Spring Boot Courses for Java developers (courses)
- Difference between @RequestParam and @PathVariable in Spring (answer)
- Top 7 Courses to learn Microservices in Java (courses)
- How to use @Bean in Spring framework (Example)
- Full 5 Spring Cloud annotations Java programmer should learn (cloud)
- 5 Courses to learn Spring Cloud for Microservices (courses)
- How Spring MVC works internally? (answer)
- Spring Data JPA @Query Example (query example)
- Spring Data JPA Repository (JpaReposistory example)
- 20+ Spring MVC Interview Questions for Programmers (answer)
- 13 Spring Boot Actuator Interview questions (boot questions)
- Difference between @Autowired and @Inject in Spring? (answer)
- Top 5 Courses to Learn and Master Spring Cloud (courses)
- 5 Courses to Learn Spring Security for Java programmers (courses)
- Top 5 Spring Boot Annotations Java Developers should know (read)
- 10 Spring MVC annotations Java developer should know (annotations)
- @SpringBootApplication vs. @EnableAutoConfiguration? (answer)
- 15 Spring Boot Interview Questions for Java Developers (questions)
- Difference between @Component, @Service, and @Controller in Spring (answer)
P. S. - If you are a beginner and want to learn the Framework from scratch and look for some of the best online resources, you can also check out these best Spring MVC courses for beginners. This list contains free Udemy and Pluralsight courses to learn Spring MVC from scratch.
Good tutorial, thank you. What is the advantage of using H2 database? How can I connect to Spring Data JPA with my existing database on PostgreSQL server?
ReplyDeleteIn above example following record is not updated as per result shown at last:
ReplyDeleteint updatedRecords
= cardRepository.updateCardBalance(24000, "1000200010");