I have a UserEntity that has a @ManyToMany bidirectional mapping association with ConversationEntity. The issue I’m facing is when I save a detached UserEntity that has an empty conversation mapping (even though there are associated conversations in the database), I expect that the entity will be merged and the @ManyToMany mapping will be populated in the returned entity. However, the associations are not being populated in the returned entity after the merge operation.
what is happening here, am I doing something wrong ?
@Transactional
public UserEntity saveUser(UserModel userModel) {
log.debug("Saving user {}", userModel);
// Converting UserModel to UserEntity (this creates a detached entity)
UserEntity userEntity = UserEntity.from(userModel);
log.debug("Converted User Entity {}", userEntity);
// Merging the detached entity
userEntity = userRepository.saveAndFlush(userEntity);
// Refreshing the entity as a workaround
//entityManager.refresh(userEntity);
log.debug("Conversations : {}", userEntity.getConversations());
return UserEntity.toModel(userEntity);
}
@Entity
public class UserEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany(fetch = FetchType.EAGER, mappedBy = "members", cascade = {CascadeType.MERGE, CascadeType.REFRESH})
@Builder.Default
private Set<ConversationEntity> conversations = new HashSet<>();
// Other fields and methods
}
@Entity
public class ConversationEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "conversation_user",
joinColumns =
@JoinColumn(name = "conversation_id" , referencedColumnName = "id"),
inverseJoinColumns =
@JoinColumn(name = "user_id",referencedColumnName = "id") )
private Set<UserEntity> members = new HashSet<>();
// Other fields and methods
}
I have tried with modifying LAZY loading to EAGER , with no luck