I’m working on my first project with Spring Boot. I’m trying to use JPA to load and edit user and user_role tables in a MySQL database. Each user can have multiple roles.
I can query for an existing user with multiple roles, but saving a new user with one or more roles fails to save the role to the user_role table. Debug data shows the insert into user, followed by update statements to the user_role table.
The records being saved are new, so why isn’t it inserting into user_role?
I’ve tried a variety of approaches, but the below code works the best so far (reads fine, no exceptions thrown). Nothing has worked for inserting new user_role records when saving a new user record.
Code:
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
@OneToMany(fetch = FetchType.EAGER)
@JoinColumn(name = "userId")
private List<UserRole> userRoles;
...
}
@Entity
@Table(name = "user_role")
public class UserRole {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String rolename;
private Long userId;
...
}
...
User user = new User(testUserName, testUserPassword1);
user.addUserRole("test");
user.addUserRole("user");
userRepository.save(user);
...
Debug output:
insert into user (password,username) values (?,?)
binding parameter (1:VARCHAR) <- [password]
binding parameter (2:VARCHAR) <- [Test User]
update user_role set user_id=? where id=?
binding parameter (1:BIGINT) <- [27]
binding parameter (2:BIGINT) <- [null]
I’m expecting inserts with the rolename included. The user and user_role tables currently only have 1 and 2 rows in them respectively. There should be a new user record (there is), and 2 new user_role records with generated ids, and a user_id matching the new user.
Steve Rose is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.