简体   繁体   English

JPA CascadeType Persist不适用于spring数据

[英]JPA CascadeType Persist doesn't work with spring data

I have two entities, user: 我有两个实体,用户:

@Data
@EqualsAndHashCode(exclude = "id")
@Entity
@Table(name = "users")
public class User {

    @Id
    @SequenceGenerator(name = "user_id_seq_gen", sequenceName = "users_id_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_id_seq_gen")
    private long id;
    @Column(nullable = false, unique = true, length = 100)
    @NotNull
    @Length(min = 4, max = 100)
    private String email;
    @Column(nullable = false, length = 50)
    @NotNull
    @Length(min = 6, max = 100)
    private String password;

}

And verification: 并验证:

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Verification {

    @Id
    @Column(length = 20)
    private String code;

    @OneToOne(cascade = {CascadeType.PERSIST})
    private User user;

}

And I save these entities in this method: 我在这个方法中保存了这些实体:

@Transactional
    public void registerUser(User user) {
        user.setPassword(DigestUtils.md5Hex(user.getPassword()));
        String code = RandomStringUtils.random(20, true, true);
        Verification verification;
        while(true) {
            if (!verificationRepository.existsByCode(code)) {
                verification = new Verification(code, user);
                break;
            } else {
                code = RandomStringUtils.random(20, true, true);
            }
        }
        verificationRepository.save(verification);
    }

But CascadeType persist doesn't work, it throws the following exception: 但CascadeType持久化不起作用,它抛出以下异常:

org.postgresql.util.PSQLException: ERROR: null value in column "user_id" violates not-null constraint
  Подробности: Failing row contains (Oda2AolKrQXYSxuVmclO, null).

But when I change cascade type to MERGE, it works. 但是当我将级联类型更改为MERGE时,它可以工作。 And I don't understand why, because I create new User and new Verification at the same time. 我不明白为什么,因为我同时创建了新的用户和新的验证。 And first I need to save the user, then the verification. 首先我需要保存用户,然后验证。 Do you know the answer? 你知道答案吗?

Spring Data JPA uses the ID to determine if the instance is new or not. Spring Data JPA使用ID来确定实例是否是新实例。 Since it seems you are setting the id to a non-null value Spring Data JPA considers it an existing entity and calls merge instead of persist . 由于您似乎将id设置为非null值,因此Spring Data JPA将其视为现有实体,并调用merge而不是persist

Read "Saving Entities" in the Reference Documentation about how to tweak that behavior. 阅读参考文档中的“保存实体”,了解如何调整该行为。

I recommend thinking in terms of Domain Driven Design and Aggregates/Aggregate Roots in order to determine the entities which should be linked via Cascade.ALL + DELETE_ORPHAN and those without any cascading and separate repositories instead. 我建议考虑Domain Driven Design和Aggregates / Aggregate Roots,以确定应通过Cascade.ALL + DELETE_ORPHAN链接的实体以及没有任何级联和单独存储库的实体。

I recommend reading " Advancing Enterprise DDD " about the topic. 我建议阅读关于该主题的“ 推进企业DDD ”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM