Difference between merge() and persist() in JPA and Hibernate

There are following difference between merge() and persist() in JPA and Hibernate.

  • merge(entity) will be used, when entity has already existed. Merging is required only for detached entities. if entity is exists, no exception will be thrown.it will be updated or created the data.
  • persist(entity) will be used when entity has not existed and to add them to Database. If an entity with the same identifier already exists in the persistence context or database, an EntityExistsException will be thrown.
  • Here we created Student entity class with id and name.
import javax.persistence.*;
 
@Entity
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name;
	
    // getters and setters are now shown for brevity
     
}
  • Here we create saveAndFlush() method with Student class input.
  • check if student.getId() value is not equals to null then use merge method to save student data in DB,
  • else if student.getId() value is equals to null, then use persist method to save new data in DB.
public Student saveAndFlush(Student student) {
		if(student.getId()!=null) {
			entityManager.merge(student);
		}else {
			entityManager.persist(student);
		}
		entityManager.flush();
		return student;
	}