弹簧数据 jpa 约束冲突异常在保存时未发生



我有一个简单的spring-boot应用程序,我正在使用spring-data-jpa。在使用相同的 id 保存记录时,我希望它会抛出异常,但它不会抛出异常并执行代码。虽然记录没有保存在数据库中,但也不会引发异常。我希望下面的代码会转到异常块,但它直接使用创建的状态代码重新响应实体。

@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 的事件。

@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;

}

最新更新