Der spezifische Fehler:< /p>
Code: Select all
org.springframework.dao.IncorrectUpdateSemanticsDataAccessException: Failed to update entity [User[id=google-1234, externalid=1234, externalidprovider=google, name=John Doe, email=john.doe@gmail]]; Id [google-1234] not found in database
Einige Besonderheiten:
- Ich habe eine Benutzertabelle (Backend Postgres 16), die wie folgt definiert ist:
Code: Select all
@Table(name = "users")
public record User (
@Id
String id,
String externalid,
String externalidprovider,
String name,
@NotNull @Email
String email
) {}
- Der Controller:
Code: Select all
@RestController
@RequestMapping("/users")
public class UserController {
private final UserRepository userRepository;
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@ResponseStatus(HttpStatus.CREATED)
@PostMapping("/upsert-google")
User upsertGoogleUser(@AuthenticationPrincipal OAuth2User googlePrincipal) {
logger.info("Upserting google user: {}", googlePrincipal);
// Check if the user already exists
if (googlePrincipal == null) {
logger.error("Null OAuth2User principal provided");
throw new IllegalArgumentException("Invalid Google user information");
}
String userId = "google-" + googlePrincipal.getAttribute("sub");
logger.info("Upserting Google user with ID: {}", userId);
// Check if the user already exists
Optional existingUserOpt = userRepository.findById(userId);
if (existingUserOpt.isPresent()) {
User existingUser = existingUserOpt.get();
logger.info("Found existing user: {}", existingUser);
return updatedUser;
} else {
User newUser = new User(
userId,
googlePrincipal.getAttribute("sub"),
"google",
googlePrincipal.getAttribute("name"),
googlePrincipal.getAttribute("email")
);
logger.info("Creating new Google user: {}", newUser);
return userRepository.save(newUser);
}
}
- Das Repository ist nur ein erweitertes CrudRepository:
Code: Select all
public interface UserRepository extends CrudRepository {}
Code: Select all
DROP TABLE IF EXISTS Users CASCADE;
CREATE TABLE IF NOT EXISTS Users (
id TEXT PRIMARY KEY,
externalid TEXT,
externalidprovider TEXT,
name TEXT NOT NULL,
email TEXT NOT NULL,
membersince TIMESTAMP NOT NULL DEFAULT NOW(),
lastlogin TIMESTAMP NOT NULL DEFAULT NOW()
);