'Spring JPA | Duplicate entry "username" for key "..." when adding to a ManyToOne relationship

I'm currently trying to update a system which has users and user profile information working.

The idea is to keep a few versions of the profile information in certain conditions and as such I intended to switch the profile information from being identified by the user id (that is the username) to be identified by a sequentially generated id (to keep track of the order).

Previously the relationship was a simple OneToOne and now I wanted to do switch it to a OneToMany as I had done before for other cases.

Problem is the error I mentioned above whenever trying to add new profile information to the database:

Caused by: java.sql.SQLIntegrityConstraintViolationException: (conn=48) Duplicate entry 'usernameInQuestion' for key 'UK_141232asdas78k552'

The profile information class was previously this:

@Id
@Column(name = "username")
private String username;

@MapsId
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "username", referencedColumnName = "username")
private User user;

And was now changed to this:

@Id
@GeneratedValue
private Long id;

@ManyToOne
@JoinColumn(name = "username")
private User user;

While previously the User entity didn't reference the profile information and now:

@Id
@Column(name = "username", nullable = false)
private String username;

@OneToMany(mappedBy = "user", fetch = FetchType.EAGER)
private List<ProfileInformation> infos;

This occurs in the creation of profile information:

    ProfileInformation info = new ProfileInformation(infoDto, user);
    [...]
    info = profileInformationRepository.save(info);

I would need to still add the ProfileInformation to the User but the error occurs before that, I have tried that before so I expect it not to be the source of the problem, I think it is in the actual saving of the Profile Information that it expects the username mapping to be unique... but why is that?

I have no clue why doesn't this work as I have a similar relationship between the Profile Information and another entity (but in reverse, where there are many of those others entities for a single profile information) and it fully works.

PS - When talking to a friend I got reminded to add further information, I have already tried dropping the database and creating it again in fear that this was some weird limbo effect of a constraint from being previously OneToOne. This error occurs in a clean database.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source