0
CREATE TABLE `user_info` (
`user_info_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`nickname` varchar(40) NOT NULL,
`email` varchar(100) 
)

this my database table,database have A record id=1, nickname=test, email=null

UserInfo info = new UserInfo();
info.setUserInfoId(1);
info.setEmail("hello@hotmail.com");

When I update with the above code, an error Column 'nickname' cannot be null occurs!

I know this is because JPA has to perform a lookup first, but I don't want to give JPA all the values that can't be empty when updating the operation.

Additional explanation:

Assuming that my front end only sends me ID and email, how can I update it? Use SQL is feasible, but JPA must require nickname not null

How to solve this problem? thx

Erwin
  • 11
  • 3

1 Answers1

1

The way to update an existing record is to load the record, update any columns that need updating, and then save it, not by creating a new object.

UserInfo info = userInfoRepository.findById(1);
info.setEmail("hello@hotmail.com");
userInfoRepository.save(info);
David Conrad
  • 15,432
  • 2
  • 42
  • 54
  • 2
    In JPA, it's not necessary to explicitly save. – chrylis -cautiouslyoptimistic- Oct 01 '19 at 17:53
  • Assuming that my front end only sends me ID and email, how can I update it? Use SQL is feasible, but JPA must require nickname not null – Erwin Oct 01 '19 at 17:56
  • You'd need to handle that yourself. Assuming you have a Spring MVC controller to handle the request then last time I looked did not support patch operations i.e. partial update. However the Spring Data Rest extension does. See further: https://stackoverflow.com/questions/37681555/how-do-i-prevent-hibernate-from-deleting-child-objects-not-present-in-a-json-pos/39424421#39424421. So one option is to delete your controller and use the SDR auto generated endpint for basic CRUD. – Alan Hay Oct 01 '19 at 18:03
  • @BOOOMr.Z All you need is ID and email. You look up the existing record by ID, you set the email, and you save it. It already has the nickname on it. – David Conrad Oct 01 '19 at 19:37