保持OneToMany关系使用不带Join表的JPA

时间:2015-01-13 13:47:07

标签: database spring hibernate jpa spring-data

我有以下表格:

`notification_job_execution`
(`jobId`,
`createdDate`,
`messageBody`)

`notification_task_execution`
(`taskId`,
`jobId`,
`status`,
`createdDate`)

Havin oneToMany relationshop(notification_job_execution,notification_task_execution)                                                       (1..N)

我有以下实体

  @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private String jobId;
    @Temporal(TemporalType.DATE)
    private Date createdDate;
    private String messageBody;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "notificationJobEntity", cascade=CascadeType.ALL)
    private Set<NotificationTaskEntity> notificationTaskEntities = new HashSet<NotificationTaskEntity>(
            0);

@Entity
@Table(name = "notification_task_execution")
public class NotificationTaskEntity implements Serializable{

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private long taskId;

    private int jobId;


    private String status;

    @Temporal(TemporalType.DATE)
    private Date createdDate;

    @ManyToOne(optional = false)
    private NotificationJobEntity notificationJobEntity;

我使用Spring和JPA以此方式持续:

  NotificationJobEntity notificationJobEntity=new NotificationJobEntity();
        notificationJobEntity.setCreatedDate(new Date());
        notificationJobEntity.setMessageBody("hello youu");


          NotificationTaskEntity notificationTaskEntity=new NotificationTaskEntity();
          notificationTaskEntity.setCreatedDate(new Date());
          notificationTaskEntity.setStatus("success");
          notificationTaskEntity.setNotificationJobEntity(notificationJobEntity);

        notificationTaskEntity.setNotificationJobEntity(notificationJobEntity);
        notificationJobEntity.getNotificationTaskEntities().add(notificationTaskEntity);

        notificationDao.save(notificationJobEntity);

我无法在数据库中看到子记录持续存在(即notificationTaskEntity)。

我怎样才能坚持父母,并且让notificationTaskEntity持久保存到数据库?

2 个答案:

答案 0 :(得分:0)

您必须在CascadeType

中指定NotificationTaskEntity
@ManyToOne(optional = false,CascadeType.PERSIST)
    private NotificationJobEntity notificationJobEntity;

答案 1 :(得分:0)

我认为您可能只需要添加@JoinColumn注释来指示数据库表中的哪个字段代表NotificationTaskEntity的ID。

@ManyToOne(optional = false)
@JoinColumn(name = "jobid")
private NotificationJobEntity notificationJobEntity;