JPA - 使用EclipseLink保持单向一对多关系失败 [英] JPA - Persisting a Unidirectional One to Many relationship fails with EclipseLink

查看:109
本文介绍了JPA - 使用EclipseLink保持单向一对多关系失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图坚持一个非常简单的单向一对多关系,但EclipseLink(2.3.1)失败。

I'm trying to persist a very simple Unidirectional One to Many relationship, but EclipseLink (2.3.1) fails.

服务类(父):

@Entity
@Table(name = "tbl_service2")
public class Service implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="service_id")
    public long serviceID;

    @Column(name="name")
    public String name;

    @OneToMany(cascade={CascadeType.ALL})
    @JoinColumn(name="service_id", referencedColumnName="service_id")
    public Set<Parameter> parameters;
}

参数类(儿童):

(当然数据库中有service_id外键字段,它没有在类中表示,因为它是单向关系)。

Parameter Class (Child):
(Of course there is "service_id" foreign key field in the database, which is not represented in the class, as it's unidirectional relation).

@Entity
@Table(name = "tbl_service_parameters2")
public class Parameter implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="param_id")
    public long parameterID;

    @Column(name="name")
    public String name;
}

这是实体持久性的代码:

And this is the code for Entity persistence:

    Service service = new Service();
    service.parameters = new HashSet<Parameter>();
    service.name = "test";
    Parameter param = new Parameter();
    param.name = "test";
    service.parameters.add(param);
    em.persist(service);
    em.flush();

我得到这个例外:

Internal Exception: java.sql.SQLException: Field 'service_id' doesn't have a default value
Error Code: 1364
Call: INSERT INTO tbl_service_parameters2 (name) VALUES (?)
    bind => [test]

编辑:数据库字段由于数据的性质,service_id 已经(并且应该有)非空约束。

The database field service_id has (and should have) not-null constraint, due the nature of the data.

这是一个错误还是错误的代码?

Is this a bug or is something wrong in the code?

推荐答案

尝试删除Parameter表的service_id字段中的not null约束。 Eclipselink将在单独的语句中更新单向1:m连接列的外键,因此您需要禁用或延迟约束检查。使其双向将允许使用其余参数数据更新fp字段。

Try removing the not null constraint on the Parameter table's service_id field. Eclipselink will update the foreign key for unidirectional 1:m join columns in a separate statement, so you'll need to disable or delay the constraint check. Making it bidirectional will allow the fp field to be updated with the rest of the parameter data.

这篇关于JPA - 使用EclipseLink保持单向一对多关系失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆