【问题标题】:Display valid msg to user for org.hibernate.exception.ConstraintViolationException:向用户显示 org.hibernate.exception.ConstraintViolationException 的有效消息:
【发布时间】:2016-03-23 11:07:32
【问题描述】:

我是 Springs、Hibernate 和 REST API 的新手。

我怎样才能捕捉到org.hibernate.exception.ConstraintViolationException(我不想删除工厂数据,因为您在工厂上有依赖(子)数据,并向用户显示适当的消息,由于工厂存在订单而无法删除它.

请帮忙。

谢谢

这是我的代码。

MillResource.java

@RequestMapping(value = "/mills/{id}",
    method = RequestMethod.DELETE,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<Void> deleteMill(@PathVariable Long id) {
    log.debug("REST request to delete Mill : {}", id);
    millRepository.delete(id);
    log.debug(" ", id);
    return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("mill", id.toString())).build();
}

CrudRepository

void delete(ID id);

/**
 * Deletes a given entity.
 * 
 * @param entity
 * @throws IllegalArgumentException in case the given entity is {@literal null}.
 */

HeaderUtil.java

public class HeaderUtil {

    public static HttpHeaders createAlert(String message, String param) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("X-omsApp-alert", message);
        headers.add("X-omsApp-params", param);
        return headers;
    }

    public static HttpHeaders createEntityCreationAlert(String entityName, String param) {
        return createAlert("A new " + entityName + " is created with identifier " + param, param);
    }

    public static HttpHeaders createEntityUpdateAlert(String entityName, String param) {
        return createAlert("A " + entityName + " is updated with identifier " + param, param);
    }

    public static HttpHeaders createEntityDeletionAlert(String entityName, String param) {
        return createAlert("A " + entityName + " is deleted with identifier " + param, param);
    }

    public static HttpHeaders createFailureAlert(String entityName, String errorKey, String defaultMessage) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("X-omsApp-error", defaultMessage);
        headers.add("X-omsApp-params", entityName);
        return headers;
    }
}

Mill.java

    import com.fasterxml.jackson.annotation.JsonIgnore;
    import org.hibernate.annotations.Cache;
    import org.hibernate.annotations.CacheConcurrencyStrategy;

    import javax.persistence.*;
    import javax.validation.constraints.*;
    import java.io.Serializable;

    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Set;
    import java.util.Objects;

    /**
     * A Mill.
     */

    @Entity
    @Table(name = "mill")
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    public class Mill implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @NotNull
    @Size(max = 10)
    @Column(name = "code", length = 10, nullable = false)
    private String code;

    @NotNull
    @Column(name = "name", nullable = false)
    private String name;

    @OneToOne
    private Addresses addresses;

    @OneToOne
    private NoteSet notes;

    @OneToMany(mappedBy = "mill")
    @JsonIgnore
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private Set<Price> pricess = new HashSet<>();

    @OneToMany(mappedBy = "mill")
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private List<Quality> qualitiess = new ArrayList<>();

    @OneToMany(mappedBy = "mill")
    @JsonIgnore
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private Set<SimpleGsmShade> simpleGsmShadess = new HashSet<>();

    @OneToMany(mappedBy = "mill")
    @JsonIgnore
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private Set<CustomerGroup> groupss = new HashSet<>();

    @OneToMany(mappedBy = "mill")
    @JsonIgnore
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private Set<DerivedGsmShade> derivedGsmShadess = new HashSet<>();

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Addresses getAddresses() {
        return addresses;
    }

    public void setAddresses(Addresses addresses) {
        this.addresses = addresses;
    }

    public NoteSet getNotes() {
        return notes;
    }

    public void setNotes(NoteSet noteSet) {
        this.notes = noteSet;
    }

    public Set<Price> getPricess() {
        return pricess;
    }

    public void setPricess(Set<Price> prices) {
        this.pricess = prices;
    }

    public List<Quality> getQualitiess() {
        return qualitiess;
    }

    public void setQualitiess(List<Quality> qualitys) {
        this.qualitiess = qualitys;
    }

    public Set<SimpleGsmShade> getSimpleGsmShadess() {
        return simpleGsmShadess;
    }

    public void setSimpleGsmShadess(Set<SimpleGsmShade> simpleGsmShades) {
        this.simpleGsmShadess = simpleGsmShades;
    }

    public Set<CustomerGroup> getGroupss() {
        return groupss;
    }

    public void setGroupss(Set<CustomerGroup> customerGroups) {
        this.groupss = customerGroups;
    }

    public Set<DerivedGsmShade> getDerivedGsmShadess() {
        return derivedGsmShadess;
    }

    public void setDerivedGsmShadess(Set<DerivedGsmShade> derivedGsmShades) {
        this.derivedGsmShadess = derivedGsmShades;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Mill mill = (Mill) o;
        if(mill.id == null || id == null) {
            return false;
        }
        return Objects.equals(id, mill.id);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(id);
    }

    @Override
    public String toString() {
        return "Mill{" +
            "id=" + id +
            ", code='" + code + "'" +
            ", name='" + name + "'" +
            '}';
    }
}

【问题讨论】:

  • 在控制器中添加try-catch块,捕获异常,在异常中,你可以做任何你想做的动作。显示其他页面,显示错误等。您可以使用 model.addAttribute 添加错误。将模型模型作为输入参数传递给控制器​​方法。

标签: java spring hibernate rest


【解决方案1】:

基本上你必须处理异常。引入 try catch 块并输出相应的消息。

在基础级别处理异常并将其汇集到控制器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    • 2022-11-04
    • 2017-01-04
    • 2011-08-10
    • 2012-01-20
    相关资源
    最近更新 更多