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

4
  • why are you creating id when you have GenerationType.IDENTITY Commented Feb 19, 2018 at 12:14
  • I am not understanding. what you are saying .no need to create id filed in model Commented Feb 19, 2018 at 12:20
  • Don't pass id field in the json Commented Feb 19, 2018 at 12:21
  • I tried that also. same error comming Commented Feb 19, 2018 at 12:23

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.