在Spring数据的批量保存期间如何确定违规实体

时间:2018-12-18 20:38:44

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

我有下一个问题

public void batchSave(List<Entity> entities) {
        repositoryJpa.save(entities);
 }

如果实体列表包含已经存在的实体,则出现DataIntegrityViolationException。

有没有办法知道哪个实体违反了持久性? 研究spring数据源代码和DataIntegrityViolationException我可以找到可以存储错误实体的任何地方。

UPD

public class Entity {


@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "GENERATOR")
@Column(name = "ID", unique = true, nullable = false)
public Long getId() {
    return id;
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "NTRY_TABS_TABH_ID", nullable = false)
public OtherEntity getOtherEntity() {
    return otherEntity;
}

@Column(name = "SORT_KEY", nullable = false)
public String getSortKey() {
    return sortKey;
}

@Enumerated(EnumType.STRING)
@Column(name = "TYPE", nullable = false)
public OperationType getOperationType() {
    return operationType;
}

@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "activeEntryEntity")
public SortKeyEntity getSortKeyEntity() {
    return sortKeyEntity;
}

@Version
@Column(name = "VERSION", nullable = false, insertable = false)
public Long getVersion() {
    return version;
}

}

1 个答案:

答案 0 :(得分:1)

使用javax验证,您将可以执行以下操作:

import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.validation.constraints.Email;

public class User {

    @NotNull(message = "Name cannot be null")
    private String name;

    @AssertTrue
    private boolean working;

    @Size(min = 10, max = 200, message 
      = "About Me must be between 10 and 200 characters")
    private String aboutMe;

    @Min(value = 18, message = "Age should not be less than 18")
    @Max(value = 150, message = "Age should not be greater than 150")
    private int age;

    @Email(message = "Email should be valid")
    private String email;

    // standard setters and getters 
}

然后您可以像这样进行验证:

Set<ConstraintViolation<User>> violations = validator.validate(user);

看看这个: https://www.baeldung.com/javax-validation