Java处理JSON格式Post请求实现数据库用户增改与存在性校验
Hey there, let's get your upsert logic working properly. Right now your code is just saving a new user every time, but we need to check if a user with the given phone exists first—then either update their message or create a new record. Here's how to fix this step by step:
Step 1: Fix the User Entity Bug
First, I spotted a typo in your User class: the setter for message is incorrectly named setLastName instead of setMessage. That would prevent the message field from being populated correctly. Let's fix that, plus add a database-level unique constraint for phone to avoid duplicates:
@Entity @Table(name = "ApiTable", schema = "TestApi") public class User { @Id @GeneratedValue(strategy= GenerationType.AUTO) private Integer id; // Enforce unique phone numbers at the database level @Column(unique = true, nullable = false) private String phone; private String message; // Getters public String getPhone() { return phone; } public String getMessage() { return message; } // Corrected setters public void setPhone(String phone) { this.phone = phone; } public void setMessage(String message) { // Fixed method name this.message = message; } }
Step 2: Extend UserRepo to Find Users by Phone
Your current UserRepo only has default CrudRepository methods. We need a way to look up a user by their phone number. Add a custom query method to the repo:
import org.springframework.data.repository.CrudRepository; import java.util.Optional; public interface UserRepo extends CrudRepository<User, Long> { // Safely find a user by phone (returns Optional to avoid null pointers) Optional<User> findByPhone(String phone); }
Using Optional is better practice here—it makes it explicit that the user might not exist, helping you avoid unexpected null errors.
Step 3: Update the Controller Logic for Upsert
Now modify your UserController to implement the upsert flow: check for an existing user by phone, update their message if they exist, or create a new user if they don't. I also switched the return type to ResponseEntity to return proper HTTP status codes (more RESTful):
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.Optional; @RestController @RequestMapping("/users") public class UserController { @Autowired private UserRepo userRepo; @PostMapping(consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<String> createOrUpdateUser(@Valid @RequestBody User requestUserDetails) { // Look up existing user by phone Optional<User> existingUser = userRepo.findByPhone(requestUserDetails.getPhone()); if (existingUser.isPresent()) { // User exists: update their message User userToUpdate = existingUser.get(); userToUpdate.setMessage(requestUserDetails.getMessage()); userRepo.save(userToUpdate); return new ResponseEntity<>("User message updated successfully.", HttpStatus.OK); } else { // User doesn't exist: create new record userRepo.save(requestUserDetails); return new ResponseEntity<>("New user created successfully.", HttpStatus.CREATED); } } }
Step 4: Clean Up Unused Code
I noticed your KeyUser class isn't used anywhere in your current implementation. If you don't plan to use it for anything else, feel free to delete it to keep your project tidy.
That's all! Now your endpoint will correctly handle both creating new users and updating existing ones based on the phone number as the unique identifier.
内容的提问来源于stack exchange,提问作者Blacit

