Reputation: 175
my entity:
@Table("user")
public class User {
@Id
private Long user_id;
private String username;
private String password;
public User(String username, String password) {
this.username = username;
this.password = password;
}
public User() {
}
public Long getUser_id() {
return user_id;
}
public void setUser_id(Long user_id) {
this.user_id = user_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
my repository:
public interface UserRepository extends CrudRepository<User, Long> {
@Query("select * from user where username = :username")
User findByUsername(@Param("username") String username);
}
my sql for creating the user table:
CREATE TABLE `user` (
`user_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL,
`password` text NOT NULL,
PRIMARY KEY (`user_id`),
UNIQUE KEY `UINQUE_USERNAME`(`username`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
User userForRegister = new User(username, passwordEncoder.encode(password));
userRepository.save(userForRegister)
If I execute the line of 'userRepository.save(userForRegister)', I will insert an entity successfully the first time.
But, if I want to insert another user entity with different username, i will get an error:
2021-01-08 21:37:38.242 INFO 11180 --- [nio-8080-exec-8] c.k.centre.controller.UserController : Failed to execute DbAction.InsertRoot(entity=com.***.***.Entity.User@65bc9ea1, generatedId=null)
I can insert it until I delete all the data of user table. Is there any point I missed?
Upvotes: 0
Views: 488
Reputation: 2496
I think that GenerateValue would solve the problem
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id")
private Long user_id;
Also I think you should map your ther fields to database columns using @Column annotation
@Column(name = "user_id")
private Long user_id;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
Upvotes: 1
Reputation: 377
Try adding @GeneratedValue(strategy = GenerationType.IDENTITY)
to your user_id
. This tells Hibernate that id is generated by your database. You configured your database primary key as autoincrement Column. Take also a look here.
Upvotes: 0