【问题标题】:How to map one entity to different table如何将一个实体映射到不同的表
【发布时间】:2020-06-09 11:55:04
【问题描述】:

还有我的课TableOne.java

@Table(name = "table_one")
@EntityListeners(AuditingEntityListener.class)
public class TableOne {
    @Id
    @GeneratedValue(generator = "UUID")
    @GenericGenerator(
            name = "UUID",
            strategy = "org.hibernate.id.UUIDGenerator")
    @Column(name = "id", unique = true, nullable = false, updatable = false)
    private String id;

    @CreatedDate
    @Column(name = "created", nullable = false, updatable = false)
    private LocalDateTime created;

    @LastModifiedDate
    @Column(name = "modified", nullable = false)
    private LocalDateTime modified;

    @Column(name = "status_desc")
    private String statusDesc;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(table = "callers")
    private Party caller;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(table = "callee")
    private Party callee;

    ...getter/setter
}

还有Part.java

@Entity
public class Party {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false, updatable = false)
    private long id;

    @Column(name = "desc")
    private String desc;

    @Column(name = "ip")
    private String ip;

    @Column(name = "port")
    private int port;
}

TableOne.java 中的以下字段:caller、callee 包含相同的字段(id、desc、port、ip),所以我想将它们保存在两个不同的表中。例如在 calleecaller 表中。 我该怎么做?

【问题讨论】:

    标签: java hibernate spring-data-jpa spring-data hibernate-mapping


    【解决方案1】:

    您可以为此使用两个实体。只需从Party 中删除@Entity 注释并使用@MappedSuperclass 对其进行注释。然后你可以创建两个实体:

    @Entity
    @Table(name = "caller")
    public class Caller extends Party
    

    @Entity
    @Table(name = "callee")
    public class Callee extends Party
    

    两者将具有相同的字段,但将映射到两个不同的表。

    【讨论】:

    • 是的,这是解决我的问题的好方法,也很好用。谢谢!但是我不能创建很多实体。我们这里还有其他方法吗?我可以使用@SecondaryTables 吗?
    • @ArtemDanilin 不,您可以从 2 个表中组成一个实体,这里您将有 3 个:table_onecallercallee
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 2019-04-19
    • 1970-01-01
    相关资源
    最近更新 更多