Update entity java spring

How to update an entity using Spring Data JPA

In this post, we will see how to update an entity using Spring Data JPA. Consider we have an entity called Student.java.

@Entity public class Student < @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Column(name = "student_name") private String studentName; @Column(name = "roll_number") private String rollNumber; @Column(name = "university") String university; //getter & setter >

Update entity using CrudRepository save() method.

Spring Data JPA provides save() method to update the entity. The CrudRepository interface contains the save() method that is used to update an entity. The save() method also can be used to create an entity. Internally save() uses isNew() to check, entity has id or not. If id is null then it will call em.persist() otherwise, it will call em.merge().

@Repository public interface StudentRepository extends CrudRepository

 @Transactional public Student update(Student student)

Additional Note – We can also use saveAll() method to update an entity using Spring Data JPA.

See a complete example of save() and saveAll() method using Spring boot and oracle database.

Update entity using @Modifying annotation

We can also update an entity using Spring Data JPA @Modifying annotation. We need to write a query method using @Query annotations. Let’s see an example.

@Modifying @Query("update Student s SET s.studentName = :studentName WHERE s.id = :id") public void updateStudentUsingQueryAnnotation(@Param("studentName") String studentName, @Param("id") int id);

Calling repository method to update entity using @Modifying.

@Transactional public String updateStudent(Student student)

Note – Check the tutorial that explains how to write query methods using @Query and @Modifying annotations to perform crud operation.

Читайте также:  Javascript get body element

Let’s see a complete example of save() method using spring boot and MySQL.

Define maven dependency in pom.xml

 springdatajpa springdatajpa 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-parent 2.3.1.RELEASE  8 8   org.springframework.boot spring-boot-starter-web  org.springframework.batch spring-batch-core  org.springframework.boot spring-boot-starter-batch  org.springframework.boot spring-boot-starter-data-jpa  mysql mysql-connector-java   
@Entity public class Student implements Serializable

Define Service and Repository interfaces.

package com.netsurfingzone.service; import com.netsurfingzone.entity.Student; import org.springframework.stereotype.Component; import java.util.List; @Component public interface StudentService

Define the Repository interface i.e StudentRepository.java

@Repository public interface StudentRepository extends JpaRepository

@Service public class StudentServiceImpl implements StudentService < @Autowired private StudentRepository studentRepository; @Transactional public Student save(Student student) < Student createResponse = null; createResponse = studentRepository.save(student); return createResponse; >@Transactional public Student update(Student student) < Student updateResponse = studentRepository.save(student); return updateResponse; >>
@RestController @RequestMapping("/student") public class StudentController < @Autowired private StudentService studentService; @Autowired private StudentRepository studentRepository; @PostMapping("/create") public Student createStudent1(@RequestBody Student student) < Student createResponse = studentService.save(student); return createResponse; >@PutMapping("/update") public Student updateStudent(@RequestBody Student student) < Student updateResponse = studentService.update(student); return updateResponse; >>
@Configuration @EnableJpaRepositories(basePackages = "com.netsurfingzone.repository") public class JpaConfig
@SpringBootApplication @ComponentScan(basePackages = "com.netsurfingzone.*") @EntityScan("com.netsurfingzone.*") public class SpringMain < public static void main(String[] args) < SpringApplication.run(SpringMain.class, args); >>
  • Spring Data JPA example using spring boot.
  • Spring Data JPA Interview Questions and Answers.
  • What is spring data JPA and what are the benefits.
  • Sorting in Spring Data JPA using Spring Boot.
  • @Version Annotation Example In Hibernate.
  • Hibernate Validator Constraints Example Using Spring Boot.
  • @Temporal Annotation Example In Hibernate/Jpa Using Spring Boot.
  • Hibernate Table Per Concrete Class Spring Boot.
  • Hibernate Table Per Subclass Inheritance Spring Boot.
  • Hibernate Single Table Inheritance using Spring Boot.
  • One To One Mapping Annotation Example in Hibernate/JPA using Spring Boot and Oracle.
  • One To One Bidirectional Mapping Example In Hibernate/JPA Using Spring Boot and Oracle.
  • One To Many Mapping Annotation Example In Hibernate/JPA Using Spring Boot And Oracle.
  • Many To One Unidirectional Mapping In Hibernate/JPA Annotation Example Using Spring Boot and Oracle.
  • One To Many Bidirectional Mapping In Hibernate/JPA Annotation Example Using Spring Boot and Oracle.
  • Many To Many Mapping Annotation Example In Hibernate/JPA Using Spring Boot And Oracle.

Источник

How to update an entity with spring data jpa?

Updating an entity with Spring Data JPA can sometimes be challenging, especially if you are new to the framework. JPA (Java Persistence API) is a specification that provides a way to persist Java objects into a relational database. Spring Data JPA is a Spring framework project that makes it easier to implement JPA-based repositories. This can simplify the code required to implement data access logic, as well as improve the performance of the data access layer by providing various optimizations.

Method 1: Update using JPA Entity Manager

To update an entity with Spring Data JPA using the JPA Entity Manager, you can follow these steps:

@PersistenceContext private EntityManager entityManager;
MyEntity entity = entityManager.find(MyEntity.class, entityId);
entity.setProperty1(newValue1); entity.setProperty2(newValue2);

Here is the complete code example:

@Repository public class MyRepository  @PersistenceContext private EntityManager entityManager; public void updateEntity(Long entityId, String newValue1, String newValue2)  MyEntity entity = entityManager.find(MyEntity.class, entityId); entity.setProperty1(newValue1); entity.setProperty2(newValue2); entityManager.merge(entity); > >

In this example, we inject the JPA Entity Manager into our repository, retrieve the entity we want to update, update its properties, and then save the changes using the merge method.

Note that the merge method returns the updated entity, so you can use it to retrieve the updated version if needed.

That’s it! This is how you can update an entity with Spring Data JPA using the JPA Entity Manager.

Method 2: Update using JPA Repository

To update an entity using Spring Data JPA with the JpaRepository interface, you can follow these steps:

OptionalEntity> optionalEntity = repository.findById(id); if (optionalEntity.isPresent())  Entity entity = optionalEntity.get(); // update entity fields >
entity.setField1(newValue1); entity.setField2(newValue2); // set other fields as needed

Here’s the complete code example:

@Service public class EntityService  @Autowired private EntityRepository repository; public void updateEntity(Long id, String newValue1, String newValue2)  OptionalEntity> optionalEntity = repository.findById(id); if (optionalEntity.isPresent())  Entity entity = optionalEntity.get(); entity.setField1(newValue1); entity.setField2(newValue2); repository.save(entity); > > >

In the above example, EntityRepository is an interface that extends JpaRepository . The Entity class is the entity to be updated and Long is the type of its primary key.

This method is simple and straightforward, and it works well for most use cases. However, it’s worth noting that there are other ways to update entities with Spring Data JPA, such as using the @Modifying annotation with a custom query.

Method 3: Update using JPA CrudRepository

here’s how you can update an entity using spring data jpa with the crudrepository interface.

step 1: create a model

first, create a model class that represents the entity you want to update. for example, let’s create a user class:

@entity @table(name = "users") public class user  @id @generatedvalue(strategy = generationtype.identity) private long id; private string name; private string email; // constructors, getters and setters >

step 2: extend crudrepository

next, create a repository interface that extends crudrepository . this will give you access to the save() method, which can be used to update an existing entity.

@repository public interface userrepository extends crudrepositoryuser, long>  >

step 3: update the entity

to update an entity, first fetch it from the database using the findbyid() method. then, modify the properties of the entity and call the save() method to update it in the database.

@service public class userservice  @autowired private userrepository userrepository; public user updateuser(long id, user user)  optionaluser> optionaluser = userrepository.findbyid(id); if (optionaluser.ispresent())  user existinguser = optionaluser.get(); existinguser.setname(user.getname()); existinguser.setemail(user.getemail()); return userrepository.save(existinguser); > else  throw new runtimeexception("user not found with id " + id); > > >

in the above example, we are fetching the user entity with the given id using the findbyid() method. if the entity exists, we are modifying its properties with the values from the user parameter and calling the save() method to update it in the database. if the entity does not exist, we are throwing a runtimeexception .

that’s it! you have successfully updated an entity using spring data jpa with the crudrepository interface.

Method 4: Update using Spring Data JPA Save Method

To update an entity with Spring Data JPA, you can use the save() method. This method updates an existing entity if it already exists in the database, or creates a new entity if it does not exist. Here are the steps to update an entity using the save() method:

OptionalEntity> entityOptional = entityRepository.findById(id);
if (entityOptional.isPresent())  Entity entity = entityOptional.get();
 entity.setField1(newField1Value); entity.setField2(newField2Value);
 entityRepository.save(entity); >

Here is the full code example:

OptionalEntity> entityOptional = entityRepository.findById(id); if (entityOptional.isPresent())  Entity entity = entityOptional.get(); entity.setField1(newField1Value); entity.setField2(newField2Value); entityRepository.save(entity); >

Note that the save() method can also be used to create a new entity by passing in a new instance of the entity class. In that case, the save() method will create a new record in the database with the values of the new entity.

Method 5: Update using JPA Native Update Query

To update an entity using JPA Native Update Query in Spring Data JPA, follow these steps:

  1. Create a repository interface that extends the JpaRepository interface provided by Spring Data JPA.
@Repository public interface MyEntityRepository extends JpaRepositoryMyEntity, Long>  >
@Modifying @Query(value = "UPDATE my_entity SET name = :name WHERE >, nativeQuery = true) void updateNameById(@Param("name") String name, @Param("id") Long id);
@Service public class MyEntityService  @Autowired private MyEntityRepository repository; public void updateNameById(String name, Long id)  repository.updateNameById(name, id); > >

In this example, we are updating the name of a MyEntity object by its ID using a native SQL update query. The @Modifying annotation tells Spring Data JPA that this query modifies the database and should be executed as an update. The @Query annotation specifies the SQL query to execute, and the nativeQuery = true attribute tells Spring Data JPA that this is a native SQL query.

The @Param annotation is used to map the method parameters to the named parameters in the SQL query. In this case, we have two parameters: name and id .

Finally, we call the updateNameById method from our service or controller to execute the update query. Note that we don’t need to write any SQL or JDBC code ourselves – Spring Data JPA takes care of all the low-level details for us.

That’s it! With these simple steps, you can update entities using JPA Native Update Query in Spring Data JPA.

Источник

Оцените статью