休眠:未更新具有单向OneToMany关系的内存对象的外键

时间:2018-08-21 14:22:18

标签: hibernate jpa hibernate-mapping

我有2个实体的以下问题-请求和参与者。一个请求可能包含多个参与者的单向关系。

 @Entity
    public class Request {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_sequence")
    @SequenceGenerator(
            name = "id_sequence",
            sequenceName = "REQUEST_SEQUENCE",
            allocationSize = 1
    )
    private Long id;

    private String requestorFullName;

    @OneToMany(cascade = CascadeType.ALL, fetch = LAZY, orphanRemoval = true)
    @JoinColumn(name = "requestId")
    private Set<Participant> participants = Sets.newHashSet();

    }

  @Entity
    public class Participant {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = 
    "id_sequence")
    @SequenceGenerator(
            name = "id_sequence",
            sequenceName = "PARTICIPANT_SEQUENCE",
            allocationSize = 1
    )
    private Long id;

    //foreign key-----------
    private Long requestId;

    }

我正在尝试与多个参与者保存新的请求。当我尝试保存新的请求实例时,Participant表中的外键会保留,但内存对象中不会反映出外键,因此字段'requestId'为null。

Request request ; //contains multiple participants
requestRepository.save(request);
//foreign key is peristed in DB, but 'requestId' in in-memory(now persisted) participants is 
//not updated, whereas both the id fields are updated.

1 个答案:

答案 0 :(得分:0)

requestId不会被填充,它被指定为OneToMany实体的Request批注中的连接列。 JPA不会像其他专栏文章那样对待它。如果您希望它具有价值,请使用request::getId