My database is composed of two tables: Organisation and User, in a ManyToOne relationship, where an organisation can hold many users.
Before I share my problem, here are my entities:
@Entity
@Table(name = "organisation")
public class OrganisationEntity {
@Id
@Column(name = "orga_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
private String name;
// Getters & Setters
}
-
@Entity
@Table(name = "\"user\"")
public class UserEntity {
@Id
@Column(name = "user_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
private String email;
@NotNull
private String firstName;
@NotNull
private String lastName;
@NotNull
private String password;
@ManyToOne(targetEntity = OrganisationEntity.class,cascade = CascadeType.ALL)
@JoinColumn(name = "orga_id")
private OrganisationEntity organisation;
// Getters & Setters
}
Here is my issue, when two users are assigned an organisation with the same name, said organisation is created twice in the Organisation table with 2 different ID's. I wish to assign an organisation's ID to a new user if it already exists.
So if users U1 & U2 are created with an organisation called O1, both should have the same orga_id and only one organisation entry should be created in the database.
How can that be achieved? And what is missing in my understanding of Hibernate?
On request, here is my service that creates the UserEntity upon user registration:
@Override
public UserInfo createUser(UserInfo newUser) {
return mapper.map(userDao.save(mapper.map(newUser)));
}
I map the object with Mapstruct to a UserEntity and send it to my DAO in order to save it in my database.
Make sure that you don't assign a new Organisation instance each time a new user is created, but rather that you first query the DB for an existing organisation by name, and re-use the resulting entity for all related users if it's already there.
Additionally, for the sake of correctness, consider adding a UNIQUE constraint to the organisation.name column.
Since you don't want different Oraganisations for different users, it's better to remove @GeneratedValue(strategy = GenerationType.AUTO) from Id attribute of OrganisationEntity. This would prevent creating more Organisation entries in DB.
Also fetch OrganisationEntity object first and assign to UserEntity