Search code examples
javaspring-bootjpamany-to-one

@manytoone jpa save problem - duplicate entry


Scenario:

Suppose I have a springboot jpa app:

public class Home {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long homeId;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "ownerId")
    private Owner owner;

    // attributes & other methods
} 

public class Owner {
    private String ownerId;         // not auto-generated
    // attributes and methods
}

What happens is I can save the first Home (and Owner if not in mysql db) with my springboot app:

So something like: homeRepository.save(myhome); // myhome is a home object populated with values

Now the problem is when I try to save another home for the same owner, it throws an exception:

org.springframework.dao.DataIntegrityViolationException: could not execute statement [Duplicate entry '741202' for key 'owner.PRIMARY'] [insert into ....

So what it basically tells me is that when trying to save 'new home' it see owner already exists and cannot do an insert because it will be a duplicate primary violation.

I have searched online for some help for a workaround for @manytoone, jpa, bi-directional, changing the cascade.save_update which seems to be deprecated etc with no luck.

Any suggestions would be appreciated.


Solution

  • I think the usage of CascadeType.ALL with @ManyToOne should be avoided cuz it does not make sense to broardcast the changes from a child to its parent record. The issue with your saving also comes from CascaseType.ALL.

    I suggest that you should disable the cascade and perform the changes to 'owner' manually by its own repository class (if you need to) and then continue with the 'home' saving operation.