I'm using the single table strategy to persist data, my (example) structure looks like this:
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Musician {
@Id
private Integer id;
private String name;
// getters, setters
}
With sub-classes as such:
@Entity
public class MusicianGuitar extends Musician {
}
@Entity
public class MusicianVocals extends Musician {
}
Each sub-class also has it's own repository class which simply looks like this:
public interface MusicianGuitarRepository extends JpaRepository<MusicianGuitar, Integer> {
}
public interface MusicianVocalRepository extends JpaRepository<MusicianVocal, Integer> {
}
I'm reading a collection of them from a source, but I want to write the saving method to be re-usable.. this is what I currently have:
private void saveGuitarists(List<MusicianGuitar> guitarists) {
for (MusicianGuitar guitarist : guitarists) {
MusicianGuitar existingGuitarist = guitaristRepository.findByName(guitarist.getName());
if (existingGuitarist == null) {
MusicianGuitar newGuitarist = new MusicianGuitar();
newGuitarist.setName("Slash");
guitaristRepository.save(newGuitarist);
}
}
}
.. and similarly for saveVocalists, saveDrummers, etc
The problem is I have to write this kind of method out for every type of Musician I currently have, and will have to write it again if there's new types added later - in this example and my practical one, the objects have all the same fields, they are just of differing types. I considered passing a Musician enum type, but that doesn't make things anything simpler. I suspect there's some way I can leverage the inheritance mapping, but can't see how.. thanks in advance!