简体   繁体   中英

Spring - JPA join abstract class in abstract class

I have a problem with JPA inheritance. The database model is also specially built. It contains several tables with the same attributes (the tables were intentionally cut by country) and all these tables connect to another table (OneToOne).

Here is an example of the data model: usa_user, germany_user, austria_user. All these tables have the same attributes (id, name, address). Now the address was also built up according to the countries eg usa_address, germany_address, austria_address.

Now I don't know or have the problem that I have been mapping them correctly for a long time. I have the following:

// All Lombok Getter, Setter Args,...
@MappedSuperclass
public abstract Address {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JsonIgnore
    private Long id;


    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id", referencedColumnName = "id")
    @JsonIgnore
    private User user;

    private String name;
    private String addr_num;
    
    ...
}

// All Lombok Getter, Setter Args,...
@MappedSuperclass
public abstract User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JsonIgnore
    private Long id;


    @OneToOne(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
    @JsonIgnore
    private Address address;

    private String name;

}

@Entity
@Table(name = "usa_user")
public class UsaUser extends User {}

@Entity
@Table(name = "austria_user")
public class AustriaUser extends User {}

@Entity
@Table(name = "germany_user")
public class GermanyUser extends User {}


@Entity
@Table(name = "usa_address")
public class UsaAddress extends Address {}

@Entity
@Table(name = "austria_address")
public class AustriaAddress extends Address {}

@Entity
@Table(name = "germany_address")
public class GermanyAddress extends Address {}


But unfortunately this does not work. Every time I start it JPA notices that it can't map the Entities Address - User (which is understandable because they are not entities but abstract classes). What would be the best way to solve this? I want to avoid that I have to list the attributes in all these entities because it would be redundant.

The goal is to find out how I can use a @MappedSuperclass in a @MappedSuperclass .

MappedSuperclass is not queryable and thus also not joinable. You need to map this as an abstract entity with the table per class inheritance strategy. Just switch to @Entity on the Address and User and add @Inheritance(TABLE_PER_CLASS) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM