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

后端 未结 3 545
暗喜
暗喜 2020-11-29 22:28

I have two tables: Ta and Tb. They have exactly the same table structure but different table names.

I try to create one entity class to map

3条回答
  •  旧巷少年郎
    2020-11-29 22:54

    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 {
    ...
    }
    

提交回复
热议问题