insert roles values('1','ROLE_USER');
public User join(User user){
// password 암호화
String encodedPassword = passwordEncoder.encode(user.getPassword());
user.setPassword(encodedPassword);
System.out.println("encodedPassword = " + encodedPassword);
// enabled 값 세팅
user.setEnabled(true);
Role role = new Role();
role.setId(1l);
user.getRoles().add(role);
return userRepository.save(user);
}
DDL은 다음과 같다
create table users( id BIGINT auto_increment, username varchar(50) unique, password varchar(60), enabled BIT, primary key(id) ); create table roles( id BIGINT auto_increment, name varchar(50), primary key(id) ); create table user_role( user_id BIGINT, role_id BIGINT, primary key(user_id,role_id), foreign key (user_id) REFERENCES users(id), FOREIGN KEY (role_id) REFERENCES roles(id) );
Hibernate: insert into users (enabled, password, username) values (?, ?, ?)
Hibernate: insert into user_role (user_id, role_id) values (?, ?)
2021-09-06 21:40:21.659 WARN 30924 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1452, SQLState: 23000
2021-09-06 21:40:21.659 ERROR 30924 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : Cannot add or update a child row: a foreign key constraint fails (`rest`.`user_role`, CONSTRAINT `FK859n2jvi8ivhui0rl0esws6o` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`))
2021-09-06 21:40:21.661 INFO 30924 --- [nio-8080-exec-2] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements
2021-09-06 21:40:21.696 ERROR 30924 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`rest`.`user_role`, CONSTRAINT `FK859n2jvi8ivhui0rl0esws6o` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`))


create table user_role(
user_id BIGINT,
role_id BIGINT,
primary key(user_id,role_id),
foreign key (user_id) REFERENCES users(id),
FOREIGN KEY (role_id) REFERENCES roles(id)
);
drop table user_role;
