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().

Define StudentRepository

@Repository
public interface StudentRepository extends CrudRepository<Student, Serializable> {

}

Use save() method

    @Transactional
    public Student update(Student student) {
        Student updateResponse = studentRepository.save(student);
        return updateResponse;
    }

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.

Repository code.

@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) {
    studentRepository.updateStudentUsingQueryAnnotation(student.getStudentName(), student.getId());
    return "Record updated successfully using @Modifiying and @query Named Parameter";
}

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

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

Define maven dependency in pom.xml

    <groupId>springdatajpa</groupId>
    <artifactId>springdatajpa</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.1.RELEASE</version>
    </parent>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-batch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

</project>

Define entity class

@Entity
public class Student implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "roll_number")
    private String rollNumber;

    @Column(name = "university")
    private String university;

}

Define Service and Repository interfaces.

StudentService.java

package com.netsurfingzone.service;

import com.netsurfingzone.entity.Student;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public interface StudentService {
    public Student save(Student student);
    public Student update(Student student);
}

Define the Repository interface i.e StudentRepository.java

@Repository
public interface StudentRepository extends JpaRepository<Student, Serializable> {
   
}

Define StudentServiceImpl.java

@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;
    }

}

Define controller class

@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;
    }

}

JpaConfig.java

@Configuration
@EnableJpaRepositories(basePackages = "com.netsurfingzone.repository")
public class JpaConfig {

}

Define SpringMain.java

@SpringBootApplication
@ComponentScan(basePackages = "com.netsurfingzone.*")
@EntityScan("com.netsurfingzone.*")
public class SpringMain {
    public static void main(String[] args) {
        SpringApplication.run(SpringMain.class, args);
    }
}

See save() method docs.