Hibernate One to Many Mapping试图将映射列更新为null

时间:2014-06-30 10:18:03

标签: java spring hibernate jpa annotations

我正在使用下面的映射

@Entity
@Table(name = "test")
public class TestOrder implements Serializable {

    @Id
    @Column(name = "orderid", updatable = false)
    protected Long orderId;

    @OneToMany(cascade = {CascadeType.ALL})
    @JoinColumn(name = "order_id_fk")
    private List<TestDetails> details;

//getters and setters
}

@Entity
@Table(name="test_details")
public class TestDetails implements Serializable {

    @Id
    //Generator
    @Column(name = "id", updatable = false, insertable = false)
    protected Long id;

    @Column(name="order_id_fk", updatable = false)
    private Long orderId;
//getters and setters
}

当我更新/插入数据时,它正在尝试将order_id_fk更新为null

SQL [update test_details set order_id_fk'='null where order_id_fk'='? and id'='?]; constraint [null];

非常感谢任何帮助。

使用Spring Integration更新/插入

<int-jpa:updating-outbound-gateway entity-class="com.aaaa.TestOrder" entity-manager-factory="myEntityManagerFactory" persist-mode="MERGE">
    <int-jpa:transactional propagation="REQUIRED" transaction-manager="myTransactionManager" />
</int-jpa:updating-outbound-gateway>

3 个答案:

答案 0 :(得分:11)

您需要急切地获取TestDetails实体的值。

只需使用

修改注释即可
@OneToMany(fetch = FetchType.EAGER, mappedBy="testOrder", cascade=CascadeType.ALL)

希望这会奏效。

答案 1 :(得分:4)

我运行了您的代码并且它正常工作(将@GeneratedValue(strategy = GenerationType.AUTO)添加到两个ID时)。

em.getTransaction().begin();
TestOrder to = new TestOrder();
TestDetails td1 = new TestDetails();
TestDetails td2 = new TestDetails();
TestDetails td3 = new TestDetails();
to.setDetails(Arrays.asList(new TestDetails[] {td1, td2, td3}));
em.persist(to);
em.getTransaction().commit();

跟随sqls的结果如何:

[03/07/14 10:03:30]  INFO jdbc.sqlonly: insert into test (orderid) values (1) 
[03/07/14 10:03:30]  INFO jdbc.sqlonly: insert into test_details (order_id_fk, id) values (NULL, 2) 
[03/07/14 10:03:30]  INFO jdbc.sqlonly: insert into test_details (order_id_fk, id) values (NULL, 3) 
[03/07/14 10:03:30]  INFO jdbc.sqlonly: insert into test_details (order_id_fk, id) values (NULL, 4) 
[03/07/14 10:03:30]  INFO jdbc.sqlonly: update test_details set order_id_fk=1 where id=2 
[03/07/14 10:03:30]  INFO jdbc.sqlonly: update test_details set order_id_fk=1 where id=3 
[03/07/14 10:03:30]  INFO jdbc.sqlonly: update test_details set order_id_fk=1 where id=4

因此,如果您发布的代码是您编译的代码,则TestOrder实体无法生成其ID(缺少@GeneratedValue注释)。

如果数据库为此实体生成ID(即使用自动编号),则应将@GeneratedValue设置为IDENTITY,以便让您的jpa提供程序知道它必须在之后重新读取插入的行。如果jpa提供程序无法重新读取id,则会将test_details order_id_fk列更新为null。

PS。为什么你没有在TestDetails方面设置多对一关系?

答案 2 :(得分:0)

您可能需要更改下面的实体。据我所知,如果您尝试设置列的外键,则效果最佳。

@Entity
@Table(name="test_details")
public class TestDetails implements Serializable {

    @Id
    //Generator
    @Column(name = "id", updatable = false, insertable = false)
    protected Long id;

    @Column(name="order_id_fk", updatable = false, insertable = false)
    private TestOrder orderId;
//getters and setters
}