0

Is there any way to store one JPA/Hibernate entity into many database tables?

For example there is a way to store inherited entities (more than one type of entity) in a single database table, my question is just reverse of this.

2
  • You might be able to handle this at the database level by using triggers. Commented Apr 10, 2016 at 3:05
  • 1
    perhaps look up JPA "Secondary Tables" ? Commented Apr 10, 2016 at 5:29

1 Answer 1

2

Yes, you can store one entity in multiple database tables. Just annotate your entity class with @SecondaryTable / @SecondaryTables and use the 'table' property of your field mapping annotation to map the field to a column from a specific table:

@Entity
@Table(name ="TABLE1")
@SecondaryTables({
    @SecondaryTable(name = "TABLE2", pkJoinColumns = @PrimaryKeyJoinColumn(name = "ID")),
    @SecondaryTable(name = "TABLE3", pkJoinColumns = @PrimaryKeyJoinColumn(name = "ID"))
})
public class MyEntity {
    @Id
    @Column(name = "ID") /* when no table property is given, the primary table is used which is TABLE1 */
    private Long id;

    @Column(name = "FIELD1", table = "TABLE2")
    private String field1;

    @Column(name = "FIELD2", table = "TABLE3")
    private String field2   
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.