简体   繁体   English

Java JPA存储库和多态

[英]Java JPA repository and polymorphism

I have following object model and repository in my application: 我的应用程序中有以下对象模型和存储库:

@Entity
class Vehicle {}

class Car extends Vehicle {}
class Truck extends Vehicle {}

@Repository
public interface VehicleRepository extends JpaRepository<Vehicle, Long> {}

What I'm trying to get working is following: 我想开始工作的是以下内容:

Vehicle t = new Truck();
VehicleRepository r = new VehicleRepository();
r.save(t);

How to get this code working without need of copying Truck to Vehicle object? 如何在无需将Truck复制到Vehicle对象的情况下使此代码正常工作?

Thanks! 谢谢!

As Alan Hay linked to you, you need to set up the inheritance : 当Alan Hay与您链接时,您需要设置继承:

  1. Add @Entity to all classes 将@Entity添加到所有类
  2. Add @Inheritance to your Vehicle class to enable inheritance for the entityManager, If you're not supposed to store any raw Vehicle, you can use @MappedSuperClass 将@Inheritance添加到Vehicle类以启用对EntityManager的继承,如果不应该存储任何原始Vehicle,则可以使用@MappedSuperClass

For the rest i relink the link that Alan Hay provided : https://en.wikibooks.org/wiki/Java_Persistence/Inheritance 对于其余的部分,我重新链接了Alan Hay提供的链接: https : //en.wikibooks.org/wiki/Java_Persistence/Inheritance

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM