postman 无法执行语句; SQL [不适用];条件约束[主要];嵌套异常是组织.休眠.异常.约束违例异常

oiopk7p5  于 2022-11-07  发布在  Postman
关注(0)|答案(2)|浏览(304)

SQL [不适用];约束[];
我使用Java/Sping Boot 创建了一个CRUD RESTful API应用程序。我有一个MariaDB,里面有员工列表和相关数据。我使用MySQL Workbench作为我的SQL客户端。
当运行Sping Boot 应用程序时没有错误。在我的数据库中没有错误。当我在我的数据库中获得所有工程师的API时没有错误。
我的“GET”请求工作正常;然而,“POST”没有。我无法创建一个新的员工,而不必直接插入到数据库与MySQL WB。
我希望能够通过Postman.使用API创建新员工
正如您所看到的,抛出了一个ConstraintViolationException。约束是我的主键,即“id”。我在MySQL WB中将其设置为自动递增。
下面是我的Engineer类的代码:

package engineermanagement.model;

import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;

@Entity
@Table(name = "Engineers")
@EntityListeners(AuditingEntityListener.class)
public class Engineer {

    private Long id;
    private String firstName;
    private String lastName;
    private String sid;
    private String email;
    private String manager;
    private Boolean teamLead;
    private String groupName;
    private String shift;
    private int startTime;
    private int endTime;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }

    @Column(name = "first_name", nullable = false)
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @Column(name = "last_name", nullable = false)
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Column(name = "eid", nullable = false)
    public String getEid() {
        return eid;
    }
    public void setEid(String eid) {
        this.sid = eid;
    }

    @Column(name = "email", nullable = false)
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }

    @Column(name = "manager", nullable = false)
    public String getManager() {
        return manager;
    }
    public void setManager(String manager) {
        this.manager = manager;
    }

    @Column(name = "teamlead", nullable = false)
    public Boolean getTeamLead() {
        return teamLead;
    }
    public void setTeamLead(Boolean teamLead) {
        this.teamLead = teamLead;
    }

    @Column(name = "group_name", nullable = false)
    public String getGroupName() {
        return groupName;
    }
    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }

    @Column(name = "shift", nullable = false)
    public String getShift() {
        return shift;
    }
    public void setShift(String shift) {
        this.shift = shift;
    }

    @Column(name = "start_time", nullable = false)
    public int getStartTime() {
        return startTime;
    }
    public void setStartTime(int startTime) {
        this.startTime = startTime;
    }

    @Column(name = "end_time", nullable = false)
    public int getEndTime() {
        return endTime;
    }
    public void setEndTime(int endTime) {
        this.endTime = endTime;
    }
}

这是我的EngineerController类的代码:

package jpmchase.controller;

import jpmchase.exception.*;
import jpmchase.model.Engineer;
import jpmchase.repository.EngineerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1")
public class EngineerController {

    @Autowired
    private EngineerRepository engineerRepository;

    @GetMapping("/engineers")
    public List<Engineer> getAllEngineers() {
        return engineerRepository.findAll();
    }

    @GetMapping("/engineers/{id}")
    public ResponseEntity<Engineer> getEngineerById(
            @PathVariable(value = "id") Long engineerId) throws ResourceNotFoundException {
        Engineer engineer = engineerRepository.findById(engineerId)
                .orElseThrow(() -> new ResourceNotFoundException("Engineer not found on :: "+ engineerId));
        return ResponseEntity.ok().body(engineer);
    }

    @PostMapping("/engineers")
    public Engineer createEngineer(@Valid @RequestBody Engineer engineer) {
        return engineerRepository.save(engineer);
    }

    @PutMapping("/engineers/{id}")
    public ResponseEntity<Engineer> updateEngineer(
            @PathVariable(value = "id") Long engineerId,
            @Valid @RequestBody Engineer engineerDetails) throws ResourceNotFoundException {
        Engineer engineer = engineerRepository.findById(engineerId)
                .orElseThrow(() -> new ResourceNotFoundException("Engineer not found on :: "+ engineerId));
        engineer.setId(engineerDetails.getId());
        engineer.setFirstName(engineerDetails.getFirstName());
        engineer.setLastName(engineerDetails.getLastName());
        engineer.setSid(engineerDetails.getSid());
        engineer.setEmail(engineerDetails.getEmail());
        engineer.setTeamLead(engineerDetails.getTeamLead());
        engineer.setManager(engineerDetails.getManager());
        engineer.setShift(engineerDetails.getShift());
        engineer.setStartTime(engineerDetails.getStartTime());
        engineer.setEndTime(engineerDetails.getEndTime());

//      engineer.setUpdatedAt(new Date());
        final Engineer updatedEngineer = engineerRepository.save(engineer);
        return ResponseEntity.ok(updatedEngineer);
    }

    @DeleteMapping("/engineers/{id}")
    public Map<String, Boolean> deleteEngineer(
            @PathVariable(value = "id") Long engineerId) throws Exception {
        Engineer engineer = engineerRepository.findById(engineerId)
                .orElseThrow(() -> new ResourceNotFoundException("Engineer not found on :: "+ engineerId));

        engineerRepository.delete(engineer);
        Map<String, Boolean> response = new HashMap<>();
        response.put("deleted", Boolean.TRUE);
        return response;
    }
}

使用 Postman ,我试图“张贴”一个新的“测试”员工,但由于上述约束失败。任何帮助将不胜感激...
完整堆栈跟踪:

2019-01-11 15:26:50.605  WARN 15276 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 1062, SQLState: 23000
2019-01-11 15:26:50.606 ERROR 15276 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper   : Duplicate entry '68' for key 'PRIMARY'
2019-01-11 15:26:50.606 ERROR 15276 --- [nio-8080-exec-6] o.h.i.ExceptionMapperStandardImpl        : HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]
2019-01-11 15:26:50.657  WARN 15276 --- [nio-8080-exec-6] .m.m.a.ExceptionHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [PRIMARY]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
6psbrbz9

6psbrbz91#

我也遇到了同样的问题,原因是这个o.h.engine.jdbc.spi.SqlExceptionHelper : Duplicate entry '68' for key 'PRIMARY'
Hibernate正在尝试为新的Engineer生成ID,但当它尝试遵循@GeneratedValue(strategy = GenerationType.AUTO)指定的生成策略时,它得到的ID已经存在。发生这种情况的原因很可能是您手动向Engineer表添加了新行,该表将与Hibernate下一次生成的ID值一起折叠。
此外,如果您多次尝试插入一个新的Engineer,您最终会成功,因为Hibernate会为下一个插入请求递增ID,直到它找到一个不存在的ID。
要解决此问题,您可以将Id生成策略更改为@GeneratedValue(strategy = GenerationType.IDENTITY),或者继续尝试插入,直到Hibernate获得未使用的Id值(如果您希望保持相同的生成策略)

thigvfpy

thigvfpy2#

org.hibernate.exception.ConstraintViolationException,

Exception约束违例表示您将数据库字段设置为非空、唯一等。数据库在将数据插入表之前会检查数据。如果任何一个条件不匹配,您将收到ConstraintViolationException。
在您的情况下,您有一个主键违规。所以请检查您的数据库表Engineer与“id=68”是否存在。如果它存在,请删除该行。

相关问题