当前位置: 首页 > 知识库问答 >
问题:

唯一索引或主键冲突:“public.car(ID)上的主键:在调用POST服务时

柴宏阔
2023-03-14
package com.mytaxi.controller;

import java.util.List;

import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.mytaxi.controller.mapper.CarMapper;
import com.mytaxi.datatransferobject.CarDTO;
import com.mytaxi.datatransferobject.CarDTO;
import com.mytaxi.domainobject.CarDO;
import com.mytaxi.domainvalue.Type;
import com.mytaxi.exception.ConstraintsViolationException;
import com.mytaxi.exception.EntityNotFoundException;
import com.mytaxi.service.car.CarService;


@RestController
@RequestMapping("v1/cars")
public class CarController
{

private final CarService carService;

@Autowired
public CarController(final CarService carService)
{
    this.carService = carService;
}


@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public CarDTO createCar(@Valid @RequestBody CarDTO carDTO) throws ConstraintsViolationException
{
    CarDO carDO = CarMapper.makeCarDO(carDTO);
    carDTO = CarMapper.makeCarDTO(carDO);
    carService.create(carDO);
    return carDTO;
}

java

package com.mytaxi.domainobject;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.Max;
import com.mytaxi.domainvalue.Type;

@Entity
@Table(
    name = "car",
    uniqueConstraints = @UniqueConstraint(name = "uc_licensePlate", columnNames = {"licensePlate"})
)
public class CarDO
{
@Id
@Column(nullable = false)
@GeneratedValue
private Long id;

@Column(nullable = false)
@Enumerated(EnumType.STRING)
private Type manufacturer;

@Column(nullable = false)
private String licensePlate;

@Column(nullable = false)
private Integer seatCount;

@Column(nullable = false)
private String engineType;

@Column(nullable = false)
@org.hibernate.annotations.Type(type="yes_no")
private Boolean convertible;

@Column
@Max(5)
private Integer rating;

@Column(nullable = false)
@org.hibernate.annotations.Type(type="yes_no")
private Boolean isFunctioning = true;

@Column(nullable = false)
@org.hibernate.annotations.Type(type="yes_no")
private Boolean isBooked = false;


public Boolean getIsFunctioning()
{
    return isFunctioning;
}

public void setIsFunctioning(Boolean isFunctioning)
{
    this.isFunctioning = isFunctioning;
}

public CarDO(Type manufacturer, String licensePlate, Integer seatCount, 
    String engineType, Boolean convertible)
{
    this.manufacturer = manufacturer;
    this.licensePlate = licensePlate;
    this.seatCount = seatCount;
    this.engineType = engineType;
    this.convertible = convertible;
}

public Long getId()
{
    return id;
}

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

public Type getManufacturer()
{
    return manufacturer;
}

public void setManufacturer(Type manufacturer)
{
    this.manufacturer = manufacturer;
}

public String getLicensePlate()
{
    return licensePlate;
}

public void setLicensePlate(String licensePlate)
{
    this.licensePlate = licensePlate;
}

public Integer getSeatCount()
{
    return seatCount;
}

public void setSeatCount(Integer seatCount)
{
    this.seatCount = seatCount;
}

public String getEngineType()
{
    return engineType;
}

public void setEngineType(String engineType)
{
    this.engineType = engineType;
}

public Boolean getConvertible()
{
    return convertible;
}

public void setConvertible(Boolean convertible)
{
    this.convertible = convertible;
}

public Integer getRating()
{
    return rating;
}

public void setRating(Integer rating)
{
    this.rating = rating;
}

}

cardto.java

package com.mytaxi.datatransferobject;

import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.mytaxi.domainvalue.Type;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class CarDTO

{
@JsonIgnore
private Long id;

@NotNull(message = "license plate can not be null!")
private String licensePlate;

@NotNull(message = "cartype can not be null!")
private Type carType;

@NotNull(message = "seatCount can not be null!")
private Integer seatCount;

@NotNull(message = "engineType can not be null!")
private String engineType;

private Boolean convertible;


private CarDTO()
{
}


public CarDTO(Long id, String licensePlate, Type carType, Integer seatCount, String engineType, Boolean convertible)
{
    this.id = id;
    this.licensePlate = licensePlate;
    this.carType = carType;
    this.seatCount = seatCount;
    this.engineType = engineType;
    this.convertible = convertible;
}


public static CarDTOBuilder newBuilder()
{
    return new CarDTOBuilder();
}


@JsonProperty
public Long getId()
{
    return id;
}


public String getLicensePlate()
{
    return licensePlate;
}


public Type getCarType()
{
    return carType;
}


public Integer getSeatCount()
{
    return seatCount;
}


public String getEngineType()
{
    return engineType;
}


public Boolean getConvertible()
{
    return convertible;
}

public static class CarDTOBuilder
{
    private Long id;
    private String licensePlate;
    private Type carType;
    private Integer seatCount;
    private String engineType;
    private Boolean convertible;


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


    public CarDTOBuilder licensePlate(String licensePlate)
    {
        this.licensePlate = licensePlate;
        return this;
    }


    public CarDTOBuilder setLicensePlate(String licensePlate)
    {
        this.licensePlate = licensePlate;
        return this;
    }


    public CarDTOBuilder setCarType(Type carType)
    {
        this.carType = carType;
        return this;
    }


    public CarDTOBuilder setSeatCount(Integer seatCount)
    {
        this.seatCount = seatCount;
        return this;
    }


    public CarDTOBuilder setEngineType(String engineType)
    {
        this.engineType = engineType;
        return this;
    }


    public CarDTOBuilder setConvertible(Boolean convertible)
    {
        this.convertible = convertible;
        return this;
    }

    public CarDTO createCarDTO()
    {
        return new CarDTO(id, licensePlate, carType, seatCount, engineType, convertible);

    }
}
package com.mytaxi.controller.mapper;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import com.mytaxi.datatransferobject.CarDTO;
import com.mytaxi.domainobject.CarDO;

public class CarMapper
{
    public static CarDO makeCarDO(CarDTO carDTO)
    {
        return new CarDO(carDTO.getCarType(), carDTO.getLicensePlate(),
            carDTO.getSeatCount(), carDTO.getEngineType(), carDTO.getConvertible());
    }

    public static CarDTO makeCarDTO(CarDO carDO)
    {  
        CarDTO.CarDTOBuilder carDTOBuilder = CarDTO.newBuilder()
            .setId(carDO.getId())
            .setCarType(carDO.getManufacturer())
            .licensePlate(carDO.getLicensePlate())
            .setSeatCount(carDO.getSeatCount())
            .setEngineType(carDO.getEngineType())
            .setConvertible(carDO.getConvertible());

        return carDTOBuilder.createCarDTO();
    }


    public static List<CarDTO> makeCarDTOList(Collection<CarDO> cars)
    {
        return cars.stream()
            .map(CarMapper::makeCarDTO)
            .collect(Collectors.toList());
    }
}
    package com.mytaxi.service.car;

    import java.util.List;

    import com.mytaxi.domainobject.CarDO;
    import com.mytaxi.domainvalue.Type;
    import com.mytaxi.exception.ConstraintsViolationException;
    import com.mytaxi.exception.EntityNotFoundException;

    public interface CarService
    {


        CarDO create(CarDO carDO) throws ConstraintsViolationException;


    }
 @Override
    public CarDO create(CarDO carDO) throws ConstraintsViolationException
    {
        CarDO car;
        try
        {
            car = carRepository.save(carDO);
        }
        catch (DataIntegrityViolationException e)
        {
            LOG.warn("ConstraintsViolationException while creating a driver: {}", carDO, e.getCause());
            throw new ConstraintsViolationException(e.getMessage());
        }
        return car;
    }
package com.mytaxi.dataaccessobject;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

import com.mytaxi.domainobject.CarDO;
import com.mytaxi.domainvalue.Type;


public interface CarRepository extends CrudRepository<CarDO, Long>
{

    List<CarDO> findByIsFunctioning(Boolean isFunctioning);

    CarDO findByLicensePlate(String licensePlate);

    List<CarDO> findByManufacturer(Type type);
}

唯一索引或主键冲突:由:org.h2.jdbc.jdbcsqlexception使用:唯一索引或主键冲突:“public.car(ID)上的主键”;SQL语句:插入到car(可转换,engine_type,IS_Brooking,IS_Function,license_plate,Manufactor,rating,seat_count,id)值(?,?,?,?,?,?,?,?,?,?,?,?)[23505-197]在org.h2.message.dbexception.getJDBCSQLException(dbexception.java:357)~[H2-1.4.197.jar:1.4.197]在org.h2.message.dbexception.get(dbexception.java:179)~[H2-1.4.197.jar:1.4.197]在org.h2.message.dbexception.get(dbexception.java:155)~[H2-1.4.197.jar:1.4.197]在在org.h2.mvstore.db.mvtable.addrow(Mvtable.java:732)~[H2-1.4.197.jar:1.4.197]在org.h2.commd.dml.insert.insertrows(insert.java:182)~[H2-1.4.197.jar:1.4.197]在org.h2.commd.dml.insert.updat(insert.java:134)~[H2-1.4.197.jar:1.4.197]在(command.java:261)~[H2-1.4.197.jar:1.4.197]在org.h2.jdbc.jdbc.jdbpreparedStatement.executeUpdateInternal(jdbcpreparedStatement.java:199)~[H2-1.4.197.jar:1.4.197]在org.h2.jdbc.jdbpreparedStatement.executeUpdateInternal(jdbcpreparedStatement.java:199)~[H2-1.4.197.jar:1.4.197]在AR:1.4.197]在com.zaxxer.hikari.pool.proxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)~[hikarICP-2.7.9.jar:na]在com.zaxxer.hikari.pool.hikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)~[hikarICP-2.7.9.jar:na]在...93个公共帧省略“public.car(ID)上的主键:

你知道代码有什么问题吗?

共有1个答案

燕凯旋
2023-03-14

我在@entity类中遇到了同样的问题。我的Data.sql ID与H2中自动生成的ID冲突。
我的解决方案是更改:

@GeneratedValue(strategy = GenerationType.AUTO)

@GeneratedValue(strategy = GenerationType.IDENTITY)

这样我可以保留我的data.sql文件。
这里的javadoc指示generationtype.identity“指示持久性提供程序必须使用数据库标识列为实体分配主键。

 类似资料:
  • 每当我的应用程序启动时,我总是得到以下错误消息: 将data.sql更改为: 生成以下错误消息:

  • 我是hibernate新手,我遇到了以下问题。“唯一索引或主键冲突”。问题的出现是由于错误的映射,但我花了几个小时来找出为什么会发生这种情况。 我有一个超级类叫做数据结构 然后是关联两个元素的类关联。这里省略了类的某些部分,只是为了简化它。 这个类作为两个数据结构类型类之间的中间类。像这样。 TP-协会-TP TP等级: 或者激活类 总的来说,我增加了以下内容: 当我尝试添加相同的对象时,问题就出

  • 尝试通过REST Post方法插入Student对象时得到以下错误 2020-10-08 18:50:08.799错误21708---[nio-8080-exec-7]O.A.C.C.C.[.[.[/].[dispatcherServlet]:servlet.Service()在路径[]上下文中的servlet[dispatcherServlet]引发异常[请求处理失败;嵌套异常是org.spri

  • 尝试通过REST Post方法插入学生对象时出现以下错误 2020-10-08 18:50:08.799错误21708---[nio-8080-exec-7]o. a. c. c.C.[.[.]Servlet.service()的servlet[调度Servlet]在上下文中的路径[]抛出异常[请求处理失败;嵌套异常是org.springframework.dao.数据完整性违反异常:不能执行语句

  • 我开始在我的spring managed java项目中使用flyway(我也在使用hibernate)。 我遵循了飞行路线的文档。我还配置了maven插件,一切正常。 尝试使用maven插件进行清理、初始化和迁移,一切正常。 相反,如果我尝试运行我的应用程序(其中有我的flyway bean): 我看到了: 创建数据库的模式 创建schema_version表 我的脚本创建整个数据库工作 不幸的

  • 每当应用程序启动时,我总是收到以下错误消息: 将data.sql更改为: 产生以下错误消息: