Home bidirectional one to many, foreign key not set in persisting parent
Reply: 0

bidirectional one to many, foreign key not set in persisting parent

developer
1#
developer Published in 2017-12-07 09:29:23Z

I have this two entities (Group and users):

@Entity
@Table(name = "user_groups")
public class UserGroup implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String name;

@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
@JoinTable(name = "user_groups_users", joinColumns = @JoinColumn(name = "user_groups_id"),
  inverseJoinColumns = @JoinColumn(name = "user_id"))
private Set<User> users;

// other attributes and getter/seters
}

And this is my User entity:

@Entity
@Table(name = "users")
public class User implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@ManyToOne(cascade = CascadeType.MERGE)
private UserGroup userGroup;

// other attributes and getter/seters
}

I'm using spring's conversion service to convert DTO to new entity to be persist:

@Component
public class MyConverter implements Converter<NewDto, UserGroup> {

@Override
public UserGroup convert(NewDto newDto) {
    UserGroup userGroup = new UserGroup();
    userGroup.setName(newDto.getName());

    Set<User> users = // fetched from DB

    // Set child's parent reference
    users.forEach(user -> user.setUserGroup(userGroup));

    userGroup.setUsers(users);

    return userGroup;
}
}

This newly created userGroup then passed to a simple service method to persist:

@Transactional
public void save(UserGroup userGroup) {
    groupRepository.save(userGroup);
 }

Now, group has been persisted with it's users, but in user table, parent (group) references is not set!

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.324376 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO