Issue
I am trying to write a simple app that contains one table that keeps track of payments each user has made and a second table that contains total amount each user has paid (sum of all payments). Currently, both tables have the same fields (firstName, lastName, amount) and I have mapped them from the same Java class and I have trouble mapping that class to multiple tables. Is there any simple solution to this?
@Entity
@Table(name="Payment")
public class Payment{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
@NotNull
private String firstNname;
@Column
@NotNull
private String lastNname;
@Column
@NotNull
private double amount;
... Constructor, getters and setters
}
Solution
You need:
@MappedSuperclass
public class ClassWithTheFields{
\\Not annotated with @Entity
@Id private Integer Id;
...
}
@Entity
public class EntityClass extends ClassWithTheFields{}
@Entity
public class AnotherEntityClass extends ClassWithTheFields{}
This way, both classes extending ClassWithTheFields will have the same fields, but will be mapping different tables.
You just need to put all the common fields in a class annotated with @MappedSuperclass, but not@Entity, and then extend this class in other classes annotated with @Entity.
Answered By - Pablo Fradua