My User
s are in Organisation
s in a ManyToOne
relationship, when a user is created with an existing Organisation I am trying to assign it to it without creating a new one.
In my service, here is how I create a user:
@Override
public UserInfo createUser(UserInfo newUser) {
// Check if organisation exists
OrganisationEntity orga = organisationDao.findByName(newUser.getOrganisation());
if (orga != null) {
// Organisation exists, we save it with the correct ID
return mapper.map(userDao.save(mapper.map(newUser, orga.getId())));
} else {
// Organisation does NOT exists, we save it and create a new one
return mapper.map(userDao.save(mapper.map(newUser, (long) -1)));
}
}
With my Mapper
(helping me to convert a model to an entity) being:
public UserEntity map(UserInfo userInfo, Long orgaId) {
UserEntity user = new UserEntity();
user.setEmail(userInfo.getEmail());
user.setFirstName(userInfo.getFirstName());
user.setLastName(userInfo.getLastName());
user.setPassword(userInfo.getPassword());
OrganisationEntity orga = new OrganisationEntity();
orga.setName(userInfo.getOrganisation());
// We set the organisation's ID
if (orgaId != -1)
orga.setId(orgaId);
user.setOrganisation(orga);
return user;
}
And here is my UserDao
:
@Transactional
public interface UserDao extends CrudRepository<UserEntity, Long> {
UserEntity save(UserEntity user);
}
And finally the relation in my UserEntity
:
@ManyToOne(targetEntity = OrganisationEntity.class, cascade = CascadeType.ALL)
@JoinColumn(name = "orga_id")
private OrganisationEntity organisation;
Creating a user with a new Organisation work but when I input an existing one, I get the following:
detached entity passed to persist
From my understanding it is a bidirectional consistency problem, but the answers did not help me so far.
Finally here are my Entity classes:
@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
}
and
@Entity
@Table(name = "organisation")
public class OrganisationEntity {
@Id
@Column(name = "orga_id", unique = true)
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Column(unique = true)
private String name;
// Getters & Setters
}