Spring Data JPA provides save() method to create an entity. Consider we have an entity called Student.java having a few fields id, name, rollNumber, and university and we want to create an entity using CrudRepository’s save() method. The CrudRepository’s save() method is used to create an entity as well as update an entity. Internally save() uses em.persist() method to create an entity.
@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;
//getter & setter
}
We are going to use postman to test this example. At the end of this tutorial, we should able to create an entity using the below rest endpoint.
http://localhost:9091/student/create

How to use CrudRepositry save() method to create an entity using Spring Data JPA
Define the StudentRepositoty interface extending CrudRepository
@Repository
public interface StudentRepository extends CrudRepository<Student, Serializable> {
}
StudentServiceImpl.java
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentRepository studentRepository;
@Transactional
public Student save(Student student) {
Student createResponse = studentRepository.save(student);
return createResponse;
}
}
Define controller class
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@Autowired
private StudentRepository studentRepository;
@PostMapping("/create")
public Student createStudent(@RequestBody Student student) {
Student createResponse = studentService.save(student);
return createResponse;
}
Note – Rules to define an entity in JPA
In JPA (Java Persistence API), an entity is a Java class that represents a table in a relational database. An entity class must be annotated with the @Entity annotation to be recognized as an entity by JPA. In addition to the @Entity annotation, there are several other rules that must be followed when defining an entity in JPA. These rules are:
- The entity class must have a no-argument constructor: JPA requires an entity class to have a no-argument constructor so that it can create instances of the class when retrieving data from the database.
- The entity class must have a primary key: Every entity in JPA must have a primary key. The primary key can be either a single column or a combination of columns that uniquely identify each record in the table.
- The primary key must be annotated with
@Id: In JPA, the primary key of an entity must be annotated with the@Idannotation. - The primary key must be unique: The primary key of an entity must be unique to each record in the table.
- The entity class must be serializable: In order to allow the entity class to be passed between different parts of the application, it must implement the
Serializableinterface. - The entity class must have getters and setters: In order for JPA to access the properties of the entity class, it must have public getters and setters for each property.
- The entity class must not be final: The entity class cannot be marked as
finalbecause JPA needs to be able to create proxy objects for the entity.
These rules ensure that the entity is well-defined and can be used by JPA to perform CRUD (Create, Read, Update, Delete) operations on the corresponding table in the database.
Let’s see a complete example of how to create an entity using Spring Data JPA
Create a maven project and add the dependency.
<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>springbootjdbctemplate</groupId>
<artifactId>springbootjdbctemplate</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>
Project structure

Define configuration file
package com.javatute.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@Configuration
@EnableJpaRepositories(basePackages = "com.javatute.repository")
public class JpaConfig {
}
Define entity class
package com.javatute.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@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;
//getter & setter
}
Define StudentRepository interface
package com.javatute.repository;
import com.javatute.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.io.Serializable;
import java.util.List;
@Repository
public interface StudentRepository extends JpaRepository<Student, Serializable> {
}
Define StudentService.java
package com.javatute.service;
import com.javatute.entity.Student;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public interface StudentService {
public Student save(Student student);
}
Define StudentServiceImpl.java
package com.javatute.serviceimpl;
import com.javatute.config.RestClient;
import com.javatute.entity.Student;
import com.javatute.repository.StudentRepository;
import com.javatute.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentRepository studentRepository;
@Transactional
public Student save(Student student) {
Student createResponse = studentRepository.save(student);
return createResponse;
}
}
StudentController.java
package com.javatute.controller;
import com.javatute.entity.Student;
import com.javatute.repository.StudentRepository;
import com.javatute.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@PostMapping("/create")
public Student createStudent1(@RequestBody Student student) {
Student createResponse = studentService.save(student);
return createResponse;
}
}
services.properties
spring.datasource.url=jdbc:mysql://localhost:3306/springbootcrudexample
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
server.port = 9091
SprinMain.java
package com.javatute.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.javatute.*")
@EntityScan("com.javatute.*")
public class SpringMain {
public static void main(String[] args) {
SpringApplication.run(SpringMain.class, args);
}
}
Run and test the example.
That’s all about How to create an entity using Spring Data JPA.
See docs.
Related post.
- Spring Data JPA greater than Example
- Spring Data JPA less than Example
- Spring Data JPA IsNull Example Using Spring Boot
- Spring Data findById() Vs getOne()
- Spring Data JPA CrudRepository findById()
- Spring Data JPA JpaRepository getOne()
- Spring Data CrudRepository saveAll() and findAll().
- Spring Data CrudRepository existsById()
- Spring Data JPA delete() vs deleteInBatch()
- Spring Data JPA deleteAll() Vs deleteAllInBatch()
- Spring Data JPA JpaRepository deleteAllInBatch()
- Spring Data JPA deleteInBatch() Example
- Spring Data JPA JpaRepository saveAndFlush() Example
- Spring Data JPA CrudRepository count() Example


