Spring data r2dbc update

1k Views Asked by At

I have a table with non-auto generated primary key which is basically a foreign key. So, using withId method as said in the documentation.

https://docs.spring.io/spring-data/r2dbc/docs/1.2.3/reference/html/#reference

Creating a new instance is working fine. But, updating the instance without selecting is giving duplicate error. Its not considering that as an update and trying to insert the record.

Table:

CREATE TABLE `project_contact` (
  `project_id` bigint NOT NULL,
  `first_name` varchar(25) DEFAULT NULL,
  `last_name` varchar(25) DEFAULT NULL,
  `email` varchar(45) NOT NULL,
  PRIMARY KEY (`client_id`),
  CONSTRAINT `prj_project_id` FOREIGN KEY (`project_id`) REFERENCES `project` (`project_id`)
)

Model class,

public class ProjectContact {

    @Id
    private final Long id;
    private final long projectId;
    private final String firstName;
    private final String lastName;
    private final String email;

    public static ProjectContact of(long projectId, String firstName, String lastName, String email) {
        return new ProjectContact(null, projectId, firstName, lastName, email);
    }

    
    public ProjectContact(Long id, long projectId, String firstName, String lastName, String email) {
        super();
        this.id = id;
        this.projectId = projectId;
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }

    public ProjectContact withId(Long id) {
        return new ProjectContact(id, this.projectId, this.firstName, this.lastName, this.email);
    }
}

Here, projectId is a foreign key and hence using withId.

Creating new instance works fine.

Project prj = Project.of(....);

projectRespository.save(prj);

Updating the instance without select, throws duplicate error since not setting id thru the code.

 Project prj = Project.of(....);
    
    projectRespository.save(prj);

Error :-

Caused by: io.r2dbc.spi.R2dbcDataIntegrityViolationException: Duplicate entry '15' for key 'project_contact.PRIMARY'
    at dev.miku.r2dbc.mysql.ExceptionFactory.createException(ExceptionFactory.java:94) ~[r2dbc-mysql-0.8.2.RELEASE.jar:0.8.2.RELEASE]
    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: 
Error has been observed at the following site(s):
    |_ checkpoint ⇢ SQL "INSERT INTO project_contact (project_id, first_name, last_name, email) VALUES (?, ?, ?, ?)" [DatabaseClient]
Stack trace:
        at dev.miku.r2dbc.mysql.ExceptionFactory.createException(ExceptionFactory.java:94) ~[r2dbc-mysql-0.8.2.RELEASE.jar:0.8.2.RELEASE]
        at dev.miku.r2dbc.mysql.TextQueryHandler.accept(QueryFlow.java:317) ~[r2dbc-mysql-0.8.2.RELEASE.jar:0.8.2.RELEASE]
        at dev.miku.r2dbc.mysql.TextQueryHandler.accept(QueryFlow.java:292) ~[r2dbc-mysql-0.8.2.RELEASE.jar:0.8.2.RELEASE]
0

There are 0 best solutions below