Hibernate batching doesn't work for EmbeddedId

265 views Asked by At

I load user friends (from external system) and need to save them and also save relations.

@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);

Is it true that batching won't work in this case due because of complex primary key (@EmbeddedId)?

0

There are 0 answers