Cobra
Cobra

Reputation: 31

How can I add user to other entity using Java and Hibernate

I am looking for an idea how can I add user to other entity (project) in my service. I have crud operations which can add, delete, edit users and projects, but I don't know how can I write my service code that can add user to specific project. I have many to many relation between them.

Project.java

@Builder
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Table(name = "projects")
public class Project {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Setter(AccessLevel.NONE)
    @Column(unique = true)
    private Long id;

    @Setter(AccessLevel.NONE)
    @EqualsAndHashCode.Include
    @Column(nullable = false, unique = true)
    private UUID uuid = UUID.randomUUID();

    @Column(unique = true, nullable = false, length = 254)
    private String name;
    @Column(nullable = false, length = 254)
    private String description;
    @Column()
    private LocalDate dateFrom;
    @Column
    private LocalDate dateTo;
    @Positive
    private Double budget;

    @ManyToMany(mappedBy = "projects")
    private Set<User> users = new HashSet<>();
}

User.java

@Builder
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Setter(AccessLevel.NONE)
    @Column(unique = true)
    private Long id;

    @Setter(AccessLevel.NONE)
    @EqualsAndHashCode.Include
    @Column(nullable = false, unique = true)
    private UUID uuid = UUID.randomUUID();

    @Column(unique = true, nullable = false, length = 254)
    private String login;
    @Column(nullable = false, length = 254)
    private String firstName;
    @Column(nullable = false, length = 254)
    private String lastName;
    @Enumerated(EnumType.STRING)
    private RoleType roleType;
    @Column(nullable = false, length = 254)
    private String password;
    @Email
    @Column(nullable = false, length = 254)
    private String email;
    @Positive
    private Double cost;

    @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @JoinTable(name = "users_projects",
            joinColumns = {@JoinColumn(name = "users_id")},
            inverseJoinColumns = {@JoinColumn(name = "projects_id")})
    private Set<Project> projects = new HashSet<>();
    }
}

Upvotes: 0

Views: 57

Answers (1)

Philipp
Philipp

Reputation: 531

You have to add it to the owning side of the relationship. Since in Project you use the attribute mappedBy, the owning side is User. So, to add a user to a project, you actually have to add the project to the set of projects in User.

Upvotes: 1

Related Questions