Reputation: 68
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
}
Upvotes: 2
Views: 1588
Reputation: 13041
You can try to use @SecondaryTable
annotation.
Something like this:
@Entity
@Table(name = "MY_PAYMENT")
@SecondaryTable(name = "MY_PAYMENT_DETAILS",
pkJoinColumns = @PrimaryKeyJoinColumn(name = "pd_payment_id"))
public class Payment {
@Id
@Column(name = "p_id")
private Long id;
@Column(name = "p_first_name")
private String firstNname;
// ...
@Column(name = "pd_amount", table = "MY_PAYMENT_DETAILS")
private double amount;
}
This is assumed that you have the following schema:
create table MY_PAYMENT
(
p_id number,
p_first_name varchar(200),
CONSTRAINT MY_PAYMENT_PK PRIMARY KEY(p_id)
);
create table MY_PAYMENT_DETAILS
(
pd_payment_id number,
pd_amount number,
CONSTRAINT MY_PAYMENT_DETAILS_PK PRIMARY KEY(pd_payment_id),
CONSTRAINT MY_PAYMENT_DETAILS_FK foreign key(pd_payment_id) references MY_PAYMENT(p_id)
);
See also this section of hibernate documentation.
Upvotes: 1
Reputation: 11
You should go with @MappedSuperclass. It's the easiest choice for you.
Upvotes: 1
Reputation: 389
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.
Upvotes: 1