Toms
Toms

Reputation: 15

JPA one to one mapping throws "Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)"

Hello im having issues with saving entities in spring boot, my classes look like this

@Table(name = "team")
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Data
@With
public class Team {

    @Id
    @Column
    @GeneratedValue
    private UUID id;

    @Column
    private String teamName;

    @OneToMany(cascade = CascadeType.ALL)
    private List<TeamMember> teamMembers;

    @OneToOne(mappedBy = "team")
    private InvitationLink invitationLink;
}

and

@Entity
@Data
@With
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "invitationLink")
public class InvitationLink {
    @Column
    @Id
    @GeneratedValue
    private UUID id;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "team_id", referencedColumnName = "id")
    private Team team;

    @Column
    private String invitationNumbers;
}

the problem in this situation is when i try and save these objects. Im saving them like this

@Override
    @Transactional
    public void createTeam(UserDto userDto, TeamDto teamDto) throws JSONException {
        // Some unrelated code here    
        InvitationLink invitationLink = new InvitationLink();
        invitationLink.setInvitationNumbers(StringUtils.generateShortUUID());
        invitationLink.setTeam(team);
        team.setInvitationLink(invitationLink);
        invitationLinkRepository.save(invitationLink);
        teamRepository.save(team);
        userRepository.save(user);
        teamMemberRepository.save(teamMember);
    }

The main problem is that when i try to save there entities i get error. Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) Does anybody know how to fix this? I have tried switching ways to map these entities but I didnt get anywhere, at one point i got another error thats recursion but thats completely different story...

Upvotes: 0

Views: 1696

Answers (1)

Ausgefuchster
Ausgefuchster

Reputation: 1178

In both your entities you use Cascade.ALL, which means that e.g. your InvitationLink is able to save changes for Team. Therefore when you save your InvitationLink it already updates your Team. So the solution could be to either change the Cascade or remove the redundant save calls.

Upvotes: 0

Related Questions