Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why I can't use string as id

I am trying to create a user model with a CrudRepository:

    @Entity
    public class User {
        @Id
        @GeneratedValue
        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 an 500 error every time I call findOne():

@Controller
public class UserController {
    @Autowired
    private UserRepository users;

    @Override
    @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 an long type id instead of username itself then everything works. I think it's common to use string as id. So how to make this work?

I use the embedded hsql database. I didn't wrote any sql code.

like image 618
darklord Avatar asked Jan 09 '23 10:01

darklord


1 Answers

The problem is that String username; is annotated with both @Id and @GeneratedValue. @Id means that is should be a primary key, fine it can be a String. But @GeneratedValue means that you want the system to automatically generate a new key when you create a new record. That's easy when the primary key is integer, all databases have a notion of sequence (even if the syntax is not always the same). But if you want String automatically generated keys, you will have do define your own custom generator.

Or if you have no reason for the @GeneratedValue annotation, simply remove it as suggested by Bohuslav Burghardt

like image 97
Serge Ballesta Avatar answered Jan 18 '23 07:01

Serge Ballesta