我有两个实体,用户:
@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;
}
并验证:
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Verification {
@Id
@Column(length = 20)
private String code;
@OneToOne(cascade = {CascadeType.PERSIST})
private User user;
}
我在这个方法中保存这些实体:
@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);
}
但是 CascadeType persist 不起作用,它会抛出以下异常:
org.postgresql.util.PSQLException: ERROR: null value in column "user_id" violates not-null constraint
Подробности: Failing row contains (Oda2AolKrQXYSxuVmclO, null).
但是当我将级联类型更改为 MERGE 时,它就起作用了。我不明白为什么,因为我同时创建了新的用户和新的验证。首先我需要保存用户,然后进行验证。你知道答案吗?