保存时未发生Spring Data JPA Constraint Violation异常 [英] Spring data jpa Constraint Violation exception is not happening on save

查看:131
本文介绍了保存时未发生Spring Data JPA Constraint Violation异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的spring-boot应用程序,我正在使用spring-data-jpa.在保存具有相同ID的记录时,我希望它会引发异常,但不会引发异常并执行代码.尽管该记录未保存在DB中,但是也不会引发异常.我期望下面的代码将转到异常块,但是相反,它将直接使用创建的状态代码来重现响应性.

I have a simple spring-boot application, I am using spring-data-jpa. While saving the record with the same id I am expecting it to throw the exception, but it's not throwing the exception and executing the code. Although the record is not being save in DB, but the exception is also not thrown. I am expecting the below code will go to the exception block, but instead it's directly returing the responseentity with created status code.

@PostMapping(value = "/events")
    public Object addEvent(@RequestBody Event event,HttpServletRequest request,HttpServletResponse response) {
        try {
            eventRepository.save(event);
        }catch (ConstraintViolationException e) {
            e.printStackTrace();
        }catch (Exception e) {

            return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }

        return new ResponseEntity<>(null, HttpStatus.CREATED);
    }

实体类:

package com.hackerrank.github.model;

import java.io.Serializable;
import java.sql.Timestamp;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name="EVENT")
public class Event implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = -1327610423837025202L;
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="ID", unique = true)
    private Long id;
    @Column(name="TYPE")
    private String type;
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="ACTOR_ID")
    private Actor actor;
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="REPO_ID")
    private Repo repo;
    @Column(name="CREATED")
    private Timestamp createdAt;

    public Event() {
    }

    public Event(Long id, String type, Actor actor, Repo repo, Timestamp createdAt) {
        this.id = id;
        this.type = type;
        this.actor = actor;
        this.repo = repo;
        this.createdAt = createdAt;
    }

    public Long getId() {
        return id;
    }

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

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Actor getActor() {
        return actor;
    }

    public void setActor(Actor actor) {
        this.actor = actor;
    }

    public Repo getRepo() {
        return repo;
    }

    public void setRepo(Repo repo) {
        this.repo = repo;
    }

    public Timestamp getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(Timestamp createdAt) {
        this.createdAt = createdAt;
    }
}

推荐答案

您可以创建自定义验证批注,以验证是否存在具有id的事件.

You can create a custom validation annotation in order to validate if event with id exists.

@Constraint(validatedBy = UniqueIdValidator.class)
@Retention(RUNTIME)
@Target({ FIELD, METHOD })
public @interface UniqueId {

    public String message() default "There is already event with this id!";

    public Class<?>[] groups() default {};

    public Class<? extends Payload>[] payload() default{};

}

@Component
public class UniqueIdValidator implements ConstraintValidator<UniqueId, Long>{

    @Autowired
    private EventService eventService;

    @Override
    public boolean isValid(Long value, ConstraintValidatorContext context) {
        return value != null && !eventService.isIdAlreadyInUse(value);
    }
}


@Service
public class EventService {

     @Autowired
     private EventRepository eventRepository;

     public boolean isIdAlreadyInUse(Long value) {
         return eventRepository.findById(value).isPresent();
     }

}

@Entity
@Table(name="EVENT")
public class Event implements Serializable {

    @Id  
    ...
    @UniqueId
    ...
    private Long id;


}

这篇关于保存时未发生Spring Data JPA Constraint Violation异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆