hibernate 如何将一个实体Map到两个表

xxb16uws  于 2023-10-23  发布在  其他
关注(0)|答案(1)|浏览(126)
public class Company  {

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

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(schema = "company",
        name = "company_settings",
        joinColumns = @JoinColumn(name = "company_id"))
    private List<Settings> settings;
}

航路迁移

CREATE TABLE company.company_settings (
                                                id serial primary key,
                                                ...
);

设置类

@Entity
@Table(schema = "company")
@Getter
@Setter
public class Settings {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

}

问题我所看到的

Caused by: org.postgresql.util.PSQLException: ERROR: relation "company.settings" does not exist

为什么我不想在@Table中使用表名-我还需要为另一个表使用Settings类。这将是相同的表,但用户。

public class User  {

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

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(schema = "user",
        name = "user_settings",
        joinColumns = @JoinColumn(name = "user_id"))
    private List<Settings> settings;
}

我想有两个表user_settingscompany_settings在不同的模式。可以用@JoinTable来做吗?我可以使用一个类,并为用户和公司扩展它,或者我可以为他们两个都有一个表。

n53p2ov0

n53p2ov01#

与实体类关联的表是实体类本身的特征,而不是与它有关系的其他类的特征。因此,在给定的持久性单元中,不能将一个实体类Map到多个不同的表。
但是,也许您可以使用多个不同实体的Map超类来接近您想要的内容。您可以:

// Not an entity, but contains mapping information for entity subclasses
@MappedSuperclass
@Getter
@Setter
public class Settings {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
}

@Entity
@Table(schema = "company", name = "company_settings")
@Getter
@Setter
public class CompanySettings extends Settings {

    @ManyToOne
    private Company company;
}

@Entity
@Table(schema = "company", name = "user_settings")
@Getter
@Setter
public class UserSettings extends Settings {

    @ManyToOne
    private User user;
}

CompanyUser实体需要将它们的关系Map到它们各自的Settings变体,但是您仍然可以通过这种方式减少设置实体之间的代码重复。比如说,

public class Company  {

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

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "company")
    private List<CompanySettings> settings;
}

您可以将CompanySettings es和UserSettings es一般地处理为Settings es,无论在何处,如果这样做是有意义的(不包括在CompanyUser中)。

相关问题