JPA обновить родительскую вставку дочерний - PullRequest
0 голосов
/ 19 октября 2018

Я новичок в JPA, у меня есть одна родительская и дочерняя таблица, когда когда-либо там вставляют, мне нужно обновить, чтобы записать эту активность в дочернюю таблицу.Поэтому, когда есть вставка или обновление в родительском, мне нужно вставить запись в дочерний.

Например, если есть обновление в родительском, тогда

 insert into child (c1, c2, CHNGE_DT, c3, c4, P1, c5, c6, PK) values (?, ?, ?, ?, ?, ?, ?, ?, ?)
 update parent set p1=?, p2=?, p3=?, p4=?, p5=?, p6=?, p7=?, LAST_UPD_DT = ? where p1=? and LAST_UPD_DT = ? and p3 not in(?,?)

, поэтому в JPA я пытался сделать обновление какэто

CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaUpdate<parent> crit = criteriaBuilder.createCriteriaUpdate(parent.class);
    Root<parent> candidate = crit.from(parent.class);
    Timestamp currentTimeStamp = DateUtil.getESTSystemTimeStamp();
    crit.set(candidate.get("p1"), xxxxxxx);
    crit.set(candidate.get("p2"), xxxxxxx);
    crit.set(candidate.get("p3"), xxxxxxx);
    crit.set(candidate.get("p4"), xxxxxxx);
    crit.set(candidate.get("p5"), xxxxxxx);
    crit.set(candidate.get("p6"), xxxxxxx);
    crit.set(candidate.get("p7"), xxxxxxx);
    crit.set(candidate.get("lastUpdateDate"), currentTimeStamp);

    // Prepare child start
    List<child> childList = new child<>();
    child c = new child();
    c.setc1(xxxxxx);
    c.setc2(xxxxxx);
    c.setc3(xxxxxx);
    c.setc4(xxxxxx);
    c.setc5(xxxxxx);
    c.setc5(xxxxxx);
    c.setChangeDate(currentTimeStamp);
    c.setP1();//Dont understand what to put here
    childList.add(c);
    crit.set(candidate.get("child"), childList);
    // Prepare child end

    Predicate restrictions = criteriaBuilder.equal(candidate.get("lastUpdateDate"),
            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(xxxxxxxxxxxx));
    restrictions = criteriaBuilder.and(restrictions,
            criteriaBuilder.equal(candidate.get("p1"), xxxxxxx));
    restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.not(candidate.get("p3")
            .in(xxxxx, xxxxx)));
    crit.where(restrictions);
    Query q = entityManager.createQuery(crit);
    int num = q.executeUpdate();

, если я комментирую из раздела Подготовка ребенка от начала до конца, я могу обновить родительскую запись, но наряду с обновлением мне нужно вставить запись в дочернюю таблицу с указанием родительского элемента, как это сделать.

ниже - родительские дочерние TO.

ParentTO:
@Entity
@Table(name = "Parent", schema = "XXXXX")
@Getter
@Setter
public class Parent implements Serializable {
    private static final long       serialVersionUID    = 5288911453481140793L;
    @Column(name = "P1")
    @Id
    @SequenceGenerator(name = "XXX", sequenceName = "XXXX", schema = "XXXX", allocationSize = 1)
    @GeneratedValue(generator = "XXXX")
    private Long                    p1;
    @Column(name = "P2")
    private Long                    p2;
    @Column(name = "P3")
    private Long                    p3; 
    @Column(name = "P4")
    private Long                    p4; 
    @Column(name = "P5")
    private Long                    p5; 
    @Column(name = "P6")
    private Long                    p6; 
    @Column(name = "P7")
    private Long                    p7;
    @OneToMany(mappedBy = "p1", cascade = CascadeType.ALL)
    @JsonManagedReference
    private List<Child> child;
}

ChildTO:

@Entity
@Table(name = "CHILD", schema = "XXXXX")
@Getter
@Setter
public class Child implements Serializable {
    private static final long   serialVersionUID    = 2168920063633405141L;
    @Column(name = "C1")
    @Id
    @SequenceGenerator(name = "XXXX", sequenceName = "XXXX", schema = "XXX", allocationSize = 1)
    @GeneratedValue(generator = "XXXXX")
    private Long                c1;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "P1")
    @JsonBackReference
    private Parent  p1;
    @Column(name = "C2")
    private String              c2;
    @Column(name = "C3")
    private String              c3;
    @Column(name = "C4")
    private String              c4;
    @Column(name = "C5")
    private String              c5;
}

Спасибо.Или, пожалуйста, предложите, если есть какой-либо другой способ.

1 Ответ

0 голосов
/ 08 августа 2019

Попробуйте выполнить следующие действия:

1.- Вставить запись.

2.- Получить список записей для обновления

3.- Обновить с помощью entityManager.merge () путем установки новых значений для сущности.

Недавно у меня возникли проблемы с CriteriaUpdate, поскольку он не синхронизирован с контекстом постоянства.

Вставка и обновление с помощью CriteriaBuilderJPA в том же транзакционном методе выдает ошибку «ForeignKey не существует»

...