我正在使用单表策略来保留数据,我的(示例)结构如下所示:
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Musician {
@Id
private Integer id;
private String name;
// getters, setters
}
具有此类的子类:
@Entity
public class MusicianGuitar extends Musician {
}
@Entity
public class MusicianVocals extends Musician {
}
每个子类也都有它自己的存储库类,看起来就像这样:
public interface MusicianGuitarRepository extends JpaRepository<MusicianGuitar, Integer> {
}
public interface MusicianVocalRepository extends JpaRepository<MusicianVocal, Integer> {
}
我正在从源中读取它们的集合,但是我想编写保存方法以使其可重复使用。这是我目前拥有的:
private void saveGuitarists(List<MusicianGuitar> guitarists) {
for (MusicianGuitar guitarist : guitarists) {
MusicianGuitar existingGuitarist = guitaristRepository.findByName(guitarist.getName());
if (existingGuitarist == null) {
// create MusicianGuitar and populate fields
guitaristRepository.save(newGuitarist);
}
}
}
..以及类似的saveVocalists,saveDrummers等
问题是我必须为我目前拥有的每种类型的音乐家写出这种方法,如果以后再添加新的类型,则必须再次编写该方法-在此示例和我的实际示例中,对象具有所有相同的字段,只是类型不同。我考虑过传递Musician枚举类型,但这并没有使事情变得更简单。我怀疑可以通过某种方式利用继承映射,但是看不到如何..预先感谢!
您可以尝试使用类似的东西
private void saveGuitarists(List<? extends Musician> musicians) {
for (Musician musician : musicians) {
Musician existingMusician = musicianRepository.findByName(musician.getName());
if (existingMusician == null) {
// create Musician and populate fields
musicianRepository.save(newMusician);
}
}
}