JPA, How to use the same class (entity) to map different tables?

Not sure you can do it exactly as you want but you can use inheritance to produce the same result.

AbsT has all the fields but no @Table annotation

Ta and Tb inherit from AbsT and have an @Table annotation each

Use

@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)

in AbsT.

Sample code:

@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class abstract AbsT {
    @Id Long id;
...
}

@Entity
@Table(name = "Ta")
public class Ta extends AbsT {
...
}

@Entity
@Table(name = "Tb")
public class Tb extends AbsT {
...
}

Leave a Comment