when I'm trying to save big list of entities (77832 elements) in PostgreSQL. But after performing "saveAll" method there are only 49207 entries in table (table was empty before adding items). According to debugger list size doesn't change. During saving data there are no errors in application and database log.
Here is entity classes:
@Getter
@Setter
@Entity
@Table(name = "faction")
@NoArgsConstructor
@AllArgsConstructor
public class Faction {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name", unique = true, nullable = false)
private String name;
@ManyToOne(cascade = CascadeType.MERGE, optional = false)
@JoinColumn(name = "allegiance_id", nullable = false)
private Allegiance allegiance;
@ManyToOne(cascade = CascadeType.MERGE, optional = false)
@JoinColumn(name = "government_id", nullable = false)
private Government government;
@Column(name = "is_player_faction", nullable = false)
private Boolean isPlayerFaction;
}
@Entity
@Table(name = "allegiance")
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Allegiance {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name", unique = true, nullable = false)
private String name;
}
And method which implements saving data logic:
public List<FactionDto> saveFactions(List<FactionDto> factionDtos) {
var factions = factionDtos.stream()
.map(factionMapper::toEntity)
.toList();
var governments = factionDtos.stream()
.map(FactionDto::getGovernment)
.collect(Collectors.toSet())
.stream()
.map(item -> new Government(null, item.getName()))
.collect(Collectors.toSet());
Map<String, Government> governmentMap = governmentRepository
.saveAll(governments)
.stream()
.collect(Collectors.toMap(Government::getName, item -> item));
var allegiances = factionDtos.stream()
.map(FactionDto::getAllegiance)
.collect(Collectors.toSet())
.stream()
.map(item -> new Allegiance(null, item.getName()))
.collect(Collectors.toSet());
Map<String, Allegiance> allegianceMap = allegianceRepository
.saveAll(allegiances)
.stream()
.collect(Collectors.toMap(Allegiance::getName, allegiance -> allegiance));
factions = factions.stream()
.peek(faction -> {
var allegiance = allegianceMap.get(faction.getAllegiance().getName());
faction.setAllegiance(allegiance);
var government = governmentMap.get(faction.getGovernment().getName());
faction.setGovernment(government);
})
.collect(Collectors.toList());
return factionRepository.saveAll(factions).stream()
.map(factionMapper::toDto)
.toList();
}
Debugger shows there are exactly 77832 elements in collection passed for saving. There are no duplicates
In my opinion there are should be same number of entries created or at least error message if there are conflicts