【问题标题】:Hibernate sequence increments parent id for each child insertHibernate 序列为每个子插入递增父 ID
【发布时间】:2022-09-27 17:16:48
【问题描述】:

使用休眠,插入到子级失败,并在子级上出现“参照完整性约束违规”。每个孩子的父 ID 都会递增。

// Parent: Composite primary key, one auto generated
@IdClass(PlanId.class)
public class PlanEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"PlanIdGenerator\")
    @SequenceGenerator(name = \"PlanIdGenerator\", sequenceName = \"PLAN_ID_SEQUENCE\", allocationSize = 1)
    private Long id;

    @Id
    private Long version;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = \"planEntity\", fetch = FetchType.LAZY, orphanRemoval = true) //
    private Collection<PlanGoalBucketEntity> goalBuckets = new ArrayList<>();

public void addPlanGoalBucketEntity(PlanGoalBucketEntity goalBucket) {
    goalBuckets.add(goalBucket);
    goalBucket.setPlanEntity(this);
}

public void removePosition(PlanGoalBucketEntity goalBucket) {
    goalBuckets.remove(goalBucket);
    goalBucket.setPlanEntity(null);
}
.....    
}

//Child

public class PlanGoalBucketEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(optional = false)
    @JoinColumns({ @JoinColumn(name = \"plan_id\", referencedColumnName = \"id\"),
            @JoinColumn(name = \"version\", referencedColumnName = \"version\") })
    private PlanEntity planEntity;

    .....
}

用一个 PlanGoalBucketEntity(子)插入到平面(父)就可以了。

插入具有多个子项的父项,它会因外键违规“参照完整性约束违规”而失败。插入第一个孩子很好,但第二个孩子失败了,因为它增加了第二个孩子的父 ID。

无法弄清楚出了什么问题。

    标签: java spring-boot hibernate spring-data-jpa


    【解决方案1】:

    你还没有粘贴你的 PlanId 类,但我认为它是这样的

    public class PlanId implements Serializable {
    
        public Long id;
        public Long version;
    }
    

    我复制了您的代码并进行了以下测试,我所做的只是如上所述实现 PlanId 并在您的实体中添加了必要的设置器。我正在使用 H2 DB

        @Test
        public void plan() {
            PlanEntity planEntity = new PlanEntity();
            planEntity.setVersion(1L);
    
            planEntity.addPlanGoalBucketEntity(new PlanGoalBucketEntity());
            planEntity.addPlanGoalBucketEntity(new PlanGoalBucketEntity());
    
            entityManager.getTransaction().begin();
            entityManager.persist(planEntity);
            entityManager.getTransaction().commit();
    
            // Check save of 2 plan goal buckets is successful
    
            List<PlanEntity> planEntities =
                    entityManager.createQuery(
                            "select distinct p from PlanEntity p left join fetch p.goalBuckets", PlanEntity.class)
                            .getResultList();
    
            assertEquals(1, planEntities.size());
            assertEquals(2, planEntities.iterator().next().getGoalBuckets().size());
        }
    

    【讨论】:

      猜你喜欢
      • 2015-01-24
      • 2018-06-25
      • 2011-06-04
      • 1970-01-01
      • 2023-02-01
      • 2013-03-06
      • 2020-06-18
      • 1970-01-01
      • 2011-05-25
      相关资源
      最近更新 更多