Yurii
Yurii

Reputation: 77

null value in column of relation violates not-null constraint

Here I have my Entity class:

@Entity
@Table(name = "\"categories\"")
@Data
@NoArgsConstructor
@Getter
@Setter
public class Category implements Comparable<Category>{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="category_id")
    private int id;
    @Column(name="category_name")
    private String name;
    @Override
    public int compareTo(Category category) {
        return this.id - category.getId();
    }
}

Category Service class:

@Override
public Category saveCategory(Category category) {
    return categoryRepository.save(category);
}

And here is the POST method in the CategoryController.class:

@PostMapping
    public ResponseEntity<?> saveCategory(@RequestBody Category category) {
        log.info("Handling save category: " + category);
        Category addedCategory = categoryService.saveCategory(category);
        URI location = ServletUriComponentsBuilder.fromCurrentRequest()
                .path("/{id}")
                .buildAndExpand(addedCategory.getId())
                .toUri();
        return ResponseEntity.created(location).build();
    }

The table 'categories' in the Postgress database looks like:

category_id, int, primary key, NotNull category_name, varchar(50)

Trying to execute the POST request with body {"category_id":1,"category_name":"Food"} cause the Error:

INFO 4 --- [io-41644-exec-3] c.f.d.s.controller.CategoryController    : Handling save category: Category(id=1, name=Food)
WARN 4 --- [io-41644-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: 23502
ERROR 4 --- [io-41644-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: null value in column "category_id" of relation "categories" violates not-null constraint
Detail: Failing row contains (null, Food         ).

Where is the problem?

Upvotes: 0

Views: 3941

Answers (1)

Yurii
Yurii

Reputation: 77

Just executed this query in Postgress to ensure autoindexing:

CREATE SEQUENCE categories_id_seq;

ALTER TABLE categories
ALTER COLUMN category_id SET DEFAULT nextval('categories_id_seq');

Upvotes: 1

Related Questions