Search code examples
javajpapersistencepsqlentitymanager

EntityManager tries to create existing entity


I'm creating an application that allows users to create hotel room reservations.

I have the entities room, user, reservation

These are my relationships set in entity class Reservation:

@Id
@GeneratedValue
private int id;

private Date reservationDate;   

@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Room room;

@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private User user;

When I try to save a new Reservation object containing an existing User using EntityManager.persist(), I get a PSQLException saying user with "id=..." violates Unique-Constraint »user_pkey«, because that user already exists. How do I tell EntitiyManager to not try to create that User (and Room at a later point too) as it already exists?


Solution

  • You get that error because JPA cascade the persist operation down to user which is seen as a new entity.

    To prevent this:

    reservation.setUser(entityManager.getReference(User.class, user.getId()));
    

    where getId must be replaced accordingly.

    The above code assumes you are not interested in modifying the user. Otherwise, a merge operation is needed:

    reservation.setUser(entityManager.merge(user));