Josh
Josh

Reputation: 111

Create Two JPA Tables from one Bean?

I know this is somehow a simple issue with inheritance of some sort, but I thought I would double check here to make sure. I'm doing a java baseball application, and I would ideally like to have two tables. One for TEAM batting statistics, and one for PLAYER batting stats. Even though the API I'm getting the data from has the exact same fields all the way through (runs, home_runs, batting_average, etc.)

I'm using JPA to define my tables, and I don't want to have to define two classes for my two tables. Such as..

        @Entity
        @Table(name="PLAYER_BATTING_STATS")
        public class PlayerBattingStats implements Serializable {

       //All 23 fields of data here ...

And the immediately afterwards create..

@Entity
@Table(name="TEAM_BATTING_STATS")
public class TeamBattingStats implements Serializable {
//Exact Same columns here for different table

Is there a way to create one class, but let JPA know I would like to have two separate tables? I would also have to do this for pitching and fielding, etc. So this would save me a lot of overhead.

Thanks in advance,

Upvotes: 0

Views: 258

Answers (1)

asdcamargo
asdcamargo

Reputation: 96

I believe that what you are looking to achieve is possible by having a base class with the fields that are common and map this class using @MappedSupperClass.

Base class:

@MappedSuperClass
abstract class BaseBattingStats implements Serializable
//common fields go here

Player Class:

@Entity
    @Table(name="PLAYER_BATTING_STATS")
    public class PlayerBattingStats extends BaseBattingStats implements Serializable {
//fields that are specific to Player class go here

Team Class:

@Entity
    @Table(name="TEAM_BATTING_STATS")
    public class TeamBattingStats extends BaseBattingStats implements Serializable {
//fields that are specific to Player class go here

I presume that you do have fields that are specific for these 2 classes, if all the fields are common and you just want to categorize the batting stats entries you should consider using a single class and them having an enum that references the 'type' of stats (e.g. Player or Team).

Upvotes: 1

Related Questions