gpt4 book ai didi

java - 在子级中插入新记录的多对多映射问题(JPA)

转载 作者:太空宇宙 更新时间:2023-11-04 09:58:09 24 4
gpt4 key购买 nike

我正在使用 JPA 的多对多注释。我有 3 个表 postal_masterpostal_mappingpostal_detail。我必须在 postal_detail 表中插入新记录,但该条目已存在于 postal_master 表中。

现在要实现相同的目标,我必须从 postal_master 表中获取 id,并使用现有的 postal_master 实体和 postal_detail 的新记录调用 JPA 的相同函数。新记录成功插入到 postal_detail 中,但 postal_mapping 表删除了 postal_master 实体的先前映射并插入新映射。我希望新的和以前的映射应该存在于映射表中。

@ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.ALL})
@JoinTable(name = "dbk_postal_mapping", joinColumns = @JoinColumn(name =
"postal_master_id"), inverseJoinColumns = @JoinColumn(name =
"postal_detail_id"))
private Set<PostalDetailEntity> postalDetails;

postal_master 表中,我将 id 作为主键,postal_detail 表也是如此。在postal_mapping表中,postal_master_idpostal_detail_id是外键,组合起来视为主键。

Image to Explain the scenario

我不擅长画画。如果你们不明白这个问题,请告诉我?

保存代码:

        Long postalMasterId 
=postalMasterRespository.findByCountryCodeAndPostalCode(postalMasterEntity.getCountryCode() , postalMasterEntity.getPostalCode());
if(null != postalMasterId) {
postalMasterEntity.setId(postalMasterId);
}

postalMasterRespository.save(postalMasterEntity);

域类:

邮政局长:

    @Entity
@Data
@Table(name = "dbk_postal_master")
@EqualsAndHashCode(callSuper = false, exclude = {"id", "postalDetails"})
public class PostalMasterEntity extends AuditableEntity {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String countryCode;

private String postalCode;

@Column(name = "is_active")
private Boolean active;

@ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.ALL})
@JoinTable(name = "dbk_postal_mapping", joinColumns = @JoinColumn(name = "postal_master_id"), inverseJoinColumns = @JoinColumn(name = "postal_detail_id"))
private Set<PostalDetailEntity> postalDetails;

邮政详情:

@Data
@EqualsAndHashCode(callSuper=false)
@Entity
@Table(name = "dbk_postal_detail")
public class PostalDetailEntity extends AuditableEntity {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private Long providerId;

private String centerCode;

private String accessTechnology;

private String speed;

可审计实体:

    @MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class AuditableEntity implements Serializable {

private static final long serialVersionUID = 1L;

@CreatedBy
private String createdBy;

@CreatedDate
private Date creationDate;

请告诉我,我该如何实现这一目标?

谢谢。

最佳答案

从主对象获取邮政详细信息集并在其中添加新的邮政详细信息。然后再次设置并调用save方法。

关于java - 在子级中插入新记录的多对多映射问题(JPA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53845123/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com