[英]Persisting Hibernate Inheritance Mapping using Single Table strategy
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 .. 和 saveVocalists、saveDrummers 等类似
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.
我考虑过传递一个 Musician 枚举类型,但这并没有让事情变得更简单。 I suspect there's some way I can leverage the inheritance mapping, but can't see how.. thanks in advance!
我怀疑有某种方法可以利用继承映射,但不知道如何......提前致谢!
You can try to use something like that你可以尝试使用类似的东西
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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.