我从外部系统加载用户朋友,并且需要保存他们以及保存关系。
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_id_generator")
@SequenceGenerator(name = "user_id_generator", sequenceName = "s_user_id", allocationSize = 100)
private Long id;
private String firstName;
private String lastName;
}
@Entity
public class Friends {
public Friends(Long userId, Long friendId) {
this.id = new FriendsId(userId, friendId);
}
@EmbeddedId
FriendsId id;
@Embeddable
@EqualsAndHashCode
public static class FriendsId implements Serializable {
private Long userId;
private Long friendId;
public FriendsId(Long userId, Long friendId) {
this.userId = userId;
this.friendId = friendId;
}
}
}
User user = ...
List<User> friends = loadUsers();
userRepository.saveAll(friends);
List<Friends> relations = new ArrayList<>();
for (User friend : friends) {
relations.add(user.getId(), friend.getId());
relations.add(friend.getId(), user.getId());
}
friendsRepository.saveAll(relations);
是否由于复杂的主键(@EmbeddedId)在这种情况下无法进行批处理?