【问题标题】:Persisting OneToMany relationship Using JPA without Join table使用没有连接表的 JPA 持久化 OneToMany 关系
【发布时间】:2015-01-13 13:47:06
【问题描述】:

我有以下表格:

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

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

拥有一对多关系商店(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 也持久化到数据库中?

【问题讨论】:

    标签: database spring hibernate jpa spring-data


    【解决方案1】:

    我想你可能只需要添加@JoinColumn注解来指明数据库表中哪个字段代表NotificationTaskEntity的ID。

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

    【讨论】:

    • 但我也应该在 NotificationTaskEntity 中有字段 jobId(作为字段和构造函数)?
    • 我遇到异常:列 'jobId' 指定了两次
    • @rayman 删除private int jobId,我认为你不需要它
    【解决方案2】:

    您必须在NotificationTaskEntity 中指定CascadeType

    @ManyToOne(optional = false,CascadeType.PERSIST)
        private NotificationJobEntity notificationJobEntity;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-25
      • 2020-06-15
      • 1970-01-01
      • 2011-01-06
      • 2012-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多