brgs
brgs

Reputation: 806

Multiple classes to one table JPA

Is it possible to have different classes being loaded depending on the value of the field? For each of these classes there would be a corresponding row in a database, and can be discerned by "type" field. They would all share the same interface (apply).

Upvotes: 0

Views: 1138

Answers (1)

Bunti
Bunti

Reputation: 1760

I think you can achieve this with JPA quite easily. Assume you have a "location" table and you can different rows for different types of locations such as StoreLocation and CustomerLocation for example. Then we can model this in JPA entities like below.

@Entity
@DiscriminatorColumn(name = "name of column you need to filter with")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract class LocationEntity {

}

Then we can have other more specific tables

@Entity
@DiscriminatorValue("STORE") // set the value of the column for store location rows
public class StoreLocationEntity extends LocationEntity {

}

and another one

@Entity
@DiscriminatorValue("CUSTOMER") // set the value of the column for customer location rows
public class CustomerLocationEntity extends LocationEntity {

}

Hope this example will help you to get started.

Upvotes: 5

Related Questions