Artyom Danilin
Artyom Danilin

Reputation: 123

How to map one entity to different table

There is my class 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
}

And there is 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;
}

The following fields: caller, callee inside TableOne.java contains the same fields (id,desc, port, ip), so I want to keep these in two different tables. For example inside callee and caller tables. How I can do that?

Upvotes: 0

Views: 334

Answers (1)

Andronicus
Andronicus

Reputation: 26026

You can use two entities for that. Simply remove @Entity annotation from Party and annotate it with @MappedSuperclass. Then you can create two entities:

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

and

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

Both will have the same fields, but will be mappet to two different tables.

Upvotes: 1

Related Questions