父表中的重复记录(@ManyToOne 双向关联)

时间:2021-07-24 07:35:14

标签: jpa spring-data-jpa one-to-many many-to-one bidirectional-relation

我在持久化父类 ProxyEntity 时遇到问题,我看到在代理表中添加了重复的行。知道在保存父类时,它也会保存子类(codeEntity,这是一个集合) 查看日志后,先保存父类,然后在保存子类时,它会再次保存proxyEntity的另一条记录。 (我使用的是双向关联)

ProxyEntity 类:

@Entity
@Getter
@Setter
@ToString
@Table(name = "PROXY")
public class ProxyEntity implements Persistable {

protected static final Logger logger = LoggerFactory.getLogger(ProxyEntity.class);

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_PROXY_ID")
@SequenceGenerator(name = "SEQ_PROXY_ID", sequenceName = "SEQ_PROXY_ID", allocationSize = 1)
@Column(name = "PROXY_ID")
private Long proxyId;


@OneToOne(cascade = CascadeType.MERGE)
@JoinColumn(name = "BRAND_STATUS_ID", referencedColumnName = "BRAND_STATUS_ID")
private BrandStatus brandStatus;


@Column(name = "DATE_CREATION")
private Date dateCreation;

@Column(name = "CREATED_BY")
private String createdBy;


@OneToMany( mappedBy = "proxyEntity", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
private Set<CodeEntity> codes = new HashSet<>();

@Override
public Long getId() {
    return proxyId;
}

@Override
public boolean isNew() {
    return proxyId== null;
}
}

代码实体.java

@Entity
@Getter
@Setter
@ToString
@Table(name = "CODES")
public class CodeEntity implements Persistable {

protected static final Logger logger = LoggerFactory.getLogger(CodeEntity.class);

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_CODE_ID")
@SequenceGenerator(name = "SEQ_CODE_ID", sequenceName = "SEQ_CODE_ID", allocationSize = 1)
@Column(name = "CODE_ID")
private Long codeId;

@Column(name = "CODE")
private String code;

@Column(name = "CODE_DESC")
private String codeDesc;

@Column(name = "DATE_CREATION")
private Date dateCreation;

@Column(name = "CREATED_BY")
private String createdBy;


@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "PROXY_ID")
private proxyEntity proxyEntity;

@Override
public Long getId() {
    return codeId;
}

@Override
public boolean isNew() {
    return codeId == null;
}
}

我保存每个实体的部分:

 codesLst.stream().forEach(code -> {
        CodeEntity codeEntity = new CodeEntity();
        codeEntity.setDateCreated(new Date());
        codeEntity.setCreatedBy(reatedBy);
        codeEntity.setCode(code);
        codeEntity.setProxyEntity(proxy);
        codeSet.add(codeEntity);
    });
 proxy.setCodes(codesLst);

我正在使用 Spring Data Jpa 持久化数据:

List<ProxyEntity> persistedProxies = proxyRepository.saveAll(proxyEntityList);

在代理表中,它们是重复记录: enter image description here

非常感谢您对这个问题的帮助。

谢谢

0 个答案:

没有答案
相关问题