First you will have to create an interface and extend JPARepository to inherit its save and saveAndFlush methods.
Note – JpaRepository interface extends PagingAndSortingRepository interface which further extends CrudRepository. CrudRepository extends Repository interface.
public interface UserRepository extends JpaRepository<User, Long> { }
@Data @AllArgsConstructor @NoArgsConstructor @JsonInclude(value = Include.NON_NULL) @Entity @Table(name = "user") public class User implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false, updatable = false, unique = true) private Long id; @Column(name = "first_name") private String firstName; @Column(name = "last_name") private String lastName; @Column(name = "email") private String email; @Column(name = "phone_number") private String phoneNumber; @Column(name = "gender") private String gender; @Column(name = "date_of_birth") private LocalDate dateOfBirth; @Column(name = "deleted") @org.hibernate.annotations.Type(type = "true_false") private boolean deleted; public User(Long id) { this.id = id; } }
Hibernate holds the persistable state of an entity in memory. The process of synchronizing or pushing this state to the underlying DB is called flushing.
When we use the save() method, the data associated with the save operation will not be flushed to the DB right away unless and until an explicit call to flush() or commit() method is made.
One thing we have to keep in mind here is that, if we decide to flush the data by ourselves without committing it, then the changes won’t be visible to the outside transaction unless a commit call is made in this transaction or the isolation level of the outside transaction is READ_UNCOMMITTED.
The saveAndFlush() method flushes the data immediately during the execution. Normally, we use this method when our business logic needs to read the saved changes at a later point during the same transaction but before the commit.
In your persistence layer you can then use the saveAndFlush method to save data into the database.
User user = new User(); user.setDateOfBirth(LocalDate.now().minusYears(20)); user.setEmail("folaudev@gmail.com"); user.setFirstName("Folau"); user.setLastName("Kaveinga"); user.setGender("MALE"); user.setPhoneNumber("3101234567"); user = userRepository.saveAndFlush(user);