'Putting already existing entities into new entities (spring boot data jpa)
I have 2 entities. AppUser: `
@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AppUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String email;
@ManyToOne(cascade = CascadeType.ALL)
private Role role;
public AppUser(String username, String email, Role roles) {
this.username = username;
this.email = email;
this.role = roles;
}
}
and Role:
@Entity
@Data
@NoArgsConstructor
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Enumerated(EnumType.STRING)
private rolesEnum roleName;
public Role(rolesEnum roleName) {
this.roleName = roleName;
}
}
I save AppUsers to my database when the application starts:
@EventListener(ApplicationReadyEvent.class)
public void start(){
List<AppUser> users = new ArrayList<>();
users.add(new AppUser("adam","[email protected]",new Role(rolesEnum.ADMIN)));
users.add(new AppUser("maciek","[email protected]",new Role(rolesEnum.ADMIN)));
users.add(new AppUser("kuba","[email protected]",new Role(rolesEnum.USER)));
appUserRepo.saveAll(users);
}
The problem is that in a database rows from roles table are duplicated so instead of having one admin row I have 2 because I just saved two users with admin role. I don't want to add new roles to a table every time I save new user I just want to add an already existing role to a new user. Image of user table
Solution 1:[1]
Create role if not present and then save the user record.
otherwise, it will create new records.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Arun Kumar |
