Alex
Alex

Reputation: 8483

JPA & RequestFactory: Persistence of Foreign Keys

In my JPA Entity class I have:

@Entity
public class Booking {
@Id
@SequenceGenerator(name = "BOOKING", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "BOOKING")
private Integer id;

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(nullable = false)
private User user;

// ...
}

In my GWT View I have:

    MainRequestFactory.BookingRequest bookingRequest = reqFactory.bookingRequest();
    BookingProxy bookingProxy = bookingRequest.create(BookingProxy.class);
    UserProxy userProxy = bookingRequest.create(UserProxy.class);

    userProxy.setId(12);

    bookingProxy.setUser(userProxy);

    Request<Void> persistRequest = bookingRequest.persist().using(bookingProxy);
    persistRequest.fire(new Receiver<Void>() {
        @Override
        public void onSuccess(Void response) {
            GWT.log("persisted");
        }
    });

/////////////////////

Users and Bookings persistence without the User Constraint works fine. But with the above code I want/have to assign the user with the ID "12" to a newly created booking. But I cannot assign a new booking to an already existing user ID 12. I get the following error:

[EL Warning]: 2011-07-05 18:48:45.464--UnitOfWork(267787945)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.0.v20110604-r9504): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: org.firebirdsql.jdbc.FBSQLException: GDS Exception. 335544665. violation of PRIMARY or UNIQUE KEY constraint "INTEG_388" on table "USERS2"

It's because an user with the ID "12" already exists and JPA wants to create a new user with the same ID instead of just creating a new booking with the user ID "12" as its foreign key.

How can I tell RequestFactory NOT to create a new user but instead just to assign the user ID of an already existing user to a new booking entry?

Upvotes: 1

Views: 861

Answers (1)

djna
djna

Reputation: 55897

I think your analysis of the problem is correct.

Instead of creating a User, instead use an EntityManager find() or getReference() to retrieve the existing User item.

Upvotes: 4

Related Questions