that's hard. Why not to get all topics with one query (id IN)? And foreach on them, persist new UserTopic and do flush at end. This should be more optimized.