由于违反约束而中止(唯一约束失败:Category.id)Spring Boot / Angular和SQLITE DB

时间:2019-03-05 12:20:10

标签: angular spring-boot sqlite spring-data-jpa

当我从Angular向Spring Boot发送数据时,我遇到异常Abort due to constraint violation (UNIQUE constraint failed: Category.id)。 这是我在控制器中的方法:

@PostMapping(consumes = { "multipart/form-data" }, value = "/saveCategory")
    @ResponseStatus(HttpStatus.OK)
    public void createCategory(@RequestPart("category") @Valid CategoryModel category,
            @RequestPart("file") @Valid @NotNull MultipartFile file) {
        String fileName = fileStorageService.storeFile(file);
        String fileURL = ServletUriComponentsBuilder.fromCurrentContextPath().path("/uploads/").path(fileName)
                .toUriString();

        category.setImage_path(fileURL);
        this.fileStorageService.storeFile(file);

        this.categoryRepository.insertCategory(category.getId(), category.getCategory_description(), category.getImage_path(), category.getCategory_name());;
    }

这是我的模特

@Entity
@Table(name = "Category")
@JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
public class CategoryModel {
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String category_name;
    private String category_description;
    private String image_path;

    @JsonIgnore
    @OneToMany( mappedBy = "category")
    private Set<ProductModel> category;

我的数据库: enter image description here

这是我在Angular服务上的POST方法:

   storeCategory(file: File, category: CategoryModel): Observable<HttpEvent<{}>> {
        const formdata: FormData = new FormData();

        formdata.append('file', file);
        formdata.append('category', new Blob([JSON.stringify({ "id":2, "category_name": category.category_name, "category_description": category.category_description })], { type: "application/json" }))
        const url = `api/cateogry/saveCategory`;
        const req = new HttpRequest('POST', url, formdata, {
            reportProgress: true,
            responseType: 'text'
        });

        return this.http.request(req);
    }

我不知道我在哪里错。从我的Angular POST方法中,我总是发送id像2,当我发送id像null时,我有异常:

java.lang.NullPointerException: null
    at com.dar.darkozmetika.models.CategoryModel.getId(CategoryModel.java:34) ~[classes/:na]

0 个答案:

没有答案