Putting already existing entities into new entities (spring boot data jpa)

Viewed 461

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","adam@gmail.com",new Role(rolesEnum.ADMIN)));
    users.add(new AppUser("maciek","maciek@gmail.com",new Role(rolesEnum.ADMIN)));
    users.add(new AppUser("kuba","kuba@gmail.com",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

Image of role table

1 Answers

Create role if not present and then save the user record.

otherwise, it will create new records.

Related