Hi I am new to Spring Data JPA and I am wondering even though I pass the Id to the entity, the Spring data jpa is inserting instead of merge. I thought when I implement the Persistable interface and implement the two methods:
public Long getId(); public Boolean isNew(); It will automatically merge instead of persist.
I have an entity class called User like:
@Entity @Table(name = "T_USER") public class User implements Serializable, Persistable<Long> { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "USER_ID") private Long id; @Column(name = "CREATION_TIME", nullable = false) private Date creationTime; @Column(name = "FIRST_NAME", nullable = false) private String firstName; @Column(name = "LAST_NAME", nullable = false) private String lastName; @Column(name = "MODIFICATION_TIME", nullable = false) private Date modificationTime; And have another class
@Entity @Table(name = "T_USER_ROLE") public class UserRole implements Serializable, Persistable<Long> { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long roleId; @Column(name = "ROLE_NAME") private String userRole; } I have a custom repository called UserRepostory extending JpaReopistory. I am hitting the save for merge and persist as I see the implementation demonstrate that Spring Data Jpa uses above two methods to either update or insert.
@Repository public interface UserRepository extends JpaRepository<User, Long> { } I have been trying to figure out but didn't get any clue. Maybe you guys can help.
saveand Spring Data will handle it for you.@Versionmarked on entity field, which was missing when persisting. So had to populate the version field and worked. Saw your post, try adding version column and see how it reacts. Also, would suggest implementing betterequalsandhashCodeinstead of just id.