Spring Data CrudRepository save() Method

In this article, we will see about Spring Data CrudRepository save() Method using Spring Boot.

CrudRepository interface extends Repository interface. In Spring Data JPA Repository is top-level interface in hierarchy. Here we are going to see save() method of CrudRepository. The save() method has been defined as below.

S save(S entity);

The CrudRepository’s save() method is used to perform save as well as an update operation. It seems a little confusing. How save() method is doing both operations? The corresponding implementation has been given in SimpleJpaRepository.java, where persist() and merge() is getting called. If we try to save entity first time then persist() method will get invoked and if we try to update the same entity merge() will get invoked.

	public S save(S entity) {

		if (entityInformation.isNew(entity)) {
			em.persist(entity);
			return entity;
		} else {
			return em.merge(entity);
		}
	}

Note – Both persist() and merge() method has been defined in EntityManger interface.

Let’s see in below code how we are going to use the CrudRepository save() method.

package com.netsurfingzone.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.netsurfingzone.entity.Student;
import com.netsurfingzone.repository.StudentRepository;
import com.netsurfingzone.service.StudentService;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Service("studentServiceImpl")
public class StudentServiceImpl implements StudentService {

	@Autowired
	private StudentRepository studentRepository;

	@Transactional
	public Student saveStudent(Student student) {
		Student studentresponse = studentRepository.save(student);
		return studentresponse;
	}


	@Transactional
	public Student updateStudent(Student student) {
		Student studentresponse = studentRepository.save(student);
		return studentresponse;
	}
	
}

Let’s see an example of Spring Data CrudRepository save() Method where we will use save() method for creating and updating the entity.

Open eclipse and create maven project, Don’t forget to check ‘Create a simple project (skip)’ click on next.  Fill all details(GroupId – crudrepositoryexample, ArtifactId – crudrepositoryexample and name – crudrepositoryexample) and click on finish. Keep packaging as the jar.

Modify pom.xml

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>versionexample</groupId>
	<artifactId>versionexample</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>versionexample</name>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.2.RELEASE</version>
	</parent>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>

		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc6</artifactId>
			<version>11.2.0.3</version>
		</dependency>

	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
		<plugins>

			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<fork>true</fork>
					<executable>C:\Program Files\Java\jdk1.8.0_131\bin\javac.exe</executable>
				</configuration>
			</plugin>


		</plugins>
	</build>
</project>

Note – In pom.xml we have defined javac.exe path in configuration tag. You need to change accordingly i.e where you have installed JDK.

If you see any error for oracle dependency then follow these steps.


Directory structure –

Spring Data CrudRepository save() Method

Student.java

package com.netsurfingzone.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Version;

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public String getRollNumber() {
        return rollNumber;
    }

    public void setRollNumber(String rollNumber) {
        this.rollNumber = rollNumber;
    }
}

StudentController.java


package com.netsurfingzone.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.netsurfingzone.entity.Student;
import com.netsurfingzone.service.StudentService;

@RestController
@RequestMapping(value = "/student")
public class StudentController {

	@Autowired
	private StudentService studentService;

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public Student saveStudent(@RequestBody Student student) {
		Student studentResponse = (Student) studentService.saveStudent(student);
		return studentResponse;
	}
	
	@RequestMapping(value = "/update/{id}", method = RequestMethod.PUT)
	@ResponseBody
	public Student updateStudent(@RequestBody Student student, @PathVariable int id) {
		Student existingStudent = studentService.findById(id);
		if(existingStudent == null) {
			throw new RuntimeException("Record not found");
		}
		Student studentResponse = (Student) studentService.updateStudent(student);
		return studentResponse;
	}

}

StudentRepository.java – interface

package com.netsurfingzone.repository;

import java.io.Serializable;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.netsurfingzone.entity.Student;
@Repository
public interface StudentRepository extends CrudRepository<Student,Serializable> {
	public Student findById(int id);
}

StudentService.java – interface

package com.netsurfingzone.service;

import org.springframework.stereotype.Component;

import com.netsurfingzone.entity.Student;

@Component
public interface StudentService {
	public Student saveStudent(Student student);
	
	public Student findById(int id);

	public Student updateStudent(Student student);
}

StudentServiceImpl.java

package com.netsurfingzone.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.netsurfingzone.entity.Student;
import com.netsurfingzone.repository.StudentRepository;
import com.netsurfingzone.service.StudentService;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Service("studentServiceImpl")
public class StudentServiceImpl implements StudentService {

	@Autowired
	private StudentRepository studentRepository;

	@Transactional
	public Student saveStudent(Student student) {
		Student studentresponse = studentRepository.save(student);
		return studentresponse;
	}

	@Transactional
	public Student findById(int id) {
		Student studentresponse = studentRepository.findById(id);
		return studentresponse;
	}

	@Transactional
	public Student updateStudent(Student student) {
		Student studentresponse = studentRepository.save(student);
		return studentresponse;
	}
	
}

SpringMain.java

package com.netsurfingzone.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;

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

		SpringApplication.run(SpringMain.class, args);
	}

}

JpaConfig.java

package com.netsurfingzone.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

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

}

application.properties

# Connection url for the database
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.username=SYSTEM
spring.datasource.password=oracle2
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
# Show or not log for each sql query
spring.jpa.show-sql = true
 
 
spring.jpa.hibernate.ddl-auto =create
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle10gDialect
 
server.port = 9091

Let’s run the SpringMain class(run as java application).

Perform save operation first using below REST API.

http://localhost:9091/student/save


Request Data –

{
"studentName":"rakesh",
"rollNumber":"0126CS01"
}

Response data –

{
    "id": 1,
    "studentName": "rakesh_first",
    "rollNumber": "0126CS01"
}

For update the entity we will use below REST API. Let’s update the rollNumber of the student.

http://localhost:9091/student/update/1

Request Data –

{
    "id": 1,
    "studentName": "rakesh_first",
    "rollNumber": "0126CS02"
}

Response Data –

{
    "id": 1,
    "studentName": "rakesh_first",
    "rollNumber": "0126CS02"
}

That’s all about Spring Data CrudRepository save() Method Example Using Spring Boot.

You may like –

Spring Data CrudRepository  Docs.