1

I created one spring Application. I am trying to save data into database using save method of JPA Repository. i am getting Error null value in column "id" violates not-null constraint

HomeController

@RestController
public class HomeController
{    
    @Autowired
    public userRepository repository;

     @RequestMapping(value="/save2",method=RequestMethod.POST )
     public String save1(@ModelAttribute user us)
     {

         repository.save(us);

       return "sucessfull";

     }
}

user

@Entity
@Table(name="user", schema="new")
public class user implements Serializable 
{

private static final long serialVersionUID = -2956665320311624925L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer id;

@Column(name="uname")
public String uname;

@Column(name="pass")
public String pass;

Table Script

enter image description here

enter image description here

Through Postman I am trying to Insert following data

enter image description here

I am getting this error

org.postgresql.util.PSQLException: ERROR: null value in column "id" violates not-null constraint

Can Any one tell me what i am doing wrong in above code

SpringUser
  • 1,351
  • 4
  • 29
  • 59

2 Answers2

2

I see couple of issues here.

First, replace your @ModelAttribute with @RequestBody since you're sending a JSON request, it is wise to use the latter. (Read up here and here). In your case, the values from request is not passed to repository save method including Id value. That's the reason you're getting not null constraint error.

Second, since you're using GenerationType.IDENTITY strategy, you should use serial or bigserial type to let Postgres to generate your primary key.

Read up nicely written answers on IDENTITY strategy here

Ram
  • 1,743
  • 2
  • 18
  • 40
0

You defined id as an Integer field in your model class. Try to pass the value in the json as an Integer, not as a String.

{
    "id": 1,
    "uname": "abc",
    "upass": "abc"
}