【问题标题】:JPA & RequestFactory: Persistence of Foreign KeysJPA 和 RequestFactory:外键的持久性
【发布时间】:2011-07-06 01:31:59
【问题描述】:

在我的 JPA 实体类中,我有:

@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;

// ...
}

在我的 GWT 视图中,我有:

    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");
        }
    });

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

UsersBookings 没有用户约束的持久性工作正常。但是使用上面的代码,我希望/必须将 ID 为“12”的用户分配给新创建的预订。但我无法将新预订分配给已经存在的用户 ID 12。我收到以下错误:

[EL 警告]: 2011-07-05 18:48:45.464--UnitOfWork(267787945)--异常 [EclipseLink-4002](日食 持久性服务 - 2.3.0.v20110604-r9504):org.eclipse.persistence.exceptions.DatabaseException 内部异常: org.firebirdsql.jdbc.FBSQLException: GDS 例外。 335544665. 违反 PRIMARY 或 UNIQUE KEY 约束 表“USERS2”上的“INTEG_388”

这是因为 ID 为“12”的用户已经存在,而 JPA 想要创建一个具有相同 ID 的新用户,而不是仅仅创建一个以用户 ID“12”作为外键的新预订。

我如何告诉RequestFactory 不要创建新用户,而只是将现有用户的用户 ID 分配给新的预订条目?

【问题讨论】:

    标签: gwt jpa jpa-2.0 requestfactory


    【解决方案1】:

    我认为你对问题的分析是正确的。

    不是创建用户,而是使用 EntityManager find() 或 getReference() 来检索现有的用户项。

    【讨论】:

    • 您能详细说明一下吗?请记住,我只能通过 RequestFactory 的代理类与域类对话。
    • 我尝试用 setUser(Integer id) { UserController userController = new UserControllerImpl(); 替换 Booking.java 中的“setUser(User user) { this.user = user;}” this.user = userController.getReference(id);} 但我遇到了同样的错误。
    • 我不熟悉 GWT,我快速阅读文档时发现了使用 find() 而不是 create() 的示例 requestFactory.employeeRequest().findEmployee(employeeId),我是猜测,但从概念上讲,这听起来像是您需要的:查找现有条目而不是创建新条目。
    • 是的,findUser 就是解决方案!我的 GWT 代码: Request persistRequest = context.setUserReference(userId).using(bookingProxy);我的服务器端代码(预订实体): this.setUser(User.findUser(userId)); entityController.create(this);
    猜你喜欢
    • 1970-01-01
    • 2021-02-17
    • 2011-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多