Why can't I use string as id

I am trying to create a user model using CrudRepository:

    public class User {
        private String username;
        private String password;

        public String getPassword() {
            return password;

        public void setPassword(String password) {
            this.password = password;

        public String getUsername() {
            return username;

        public void setUsername(String username) {
            this.username = username;

    public interface UserRepository extends CrudRepository<User, String> {



However, I got 500 errors every time I call findOne ():

public class UserController {
    private UserRepository users;

    @RequestMapping(value="/register", method=RequestMethod.POST)
    public @ResponseBody User register(@RequestBody User userToRegister) {
        String username = userToRegister.getUsername();
        User user = users.findOne(id);
        if (user != null) {
            return null;
        User registeredUser = users.save(userToRegister);
        return registeredUser;


However, if I just switch to long type id instead of username, then everything works. I believe using the string as id. So how do you do it?

I am using hsql embedded database. I haven't written any sql code.


source to share

1 answer

The problem is that it is String username;

annotated with @Id

both @GeneratedValue

. @Id

means it should be the primary key, great, it could be a string. But it @GeneratedValue

means that you want the system to automatically generate a new key when you create a new record. It's easy when the primary key is an integer, all databases have a notion of a sequence (even if the syntax is not always the same). But if you want string auto-generated keys, you must define your own custom generator.

Or if you have no reason to annotate @GeneratedValue

, just remove it as suggested by Bohuslav Burghardt



All Articles