开发者

Hibernate two tables and one object

开发者 https://www.devze.com 2023-01-19 04:05 出处:网络
I have this situtation: Table1: tab_id field11 field12 Table2 id tab_id field21 field22 I have to create one object on this two tables for example:

I have this situtation:

Table1: 
tab_id
field11
field12


Table2
id
tab_id
field21
field22

I have to create one object on this two tables for example:

object: 

@Id
tabId

@Colummn(name="field11")
field11

@Colummn(name="field12")
field12

@Colummn(name开发者_开发技巧="field21")
field21

When i update field21 table2 should update this field, but table1 doesn't have any information about table2, only table2 hat foreign key to table1

Any idea how i should this make ?

I cannot change table structure, i can only create new class in java.


The id column in Table2 (I guess it's the PK) is annoying. But if you can get it generated upon insert, mapping both tables using a @SecondaryTable should work:

@Entity
@Table(name="TABLE1")
@SecondaryTable(name="TABLE2", pkJoinColumns = 
    @PrimaryKeyJoinColumn(name="TAB_ID", referencedColumnName="TAB_ID")
)
public class MyEntity {
    ...
    @Id @Column(name="TAB_ID")
    private Long tabId;

    @Column(name="FIELD11")
    private int field11;

    @Column(name="FIELD12")
    private int field12;

    @Column(name="FIELD21", table="TABLE2")
    private int field21;
    ...
}

If you can't, I'm afraid you'll have to map 2 classes (with a OneToOne relation).

References

  • JPA Wikibook
    • Advanced Table mappings
  • JPA 1.0 specification
    • Section 9.1.2 "SecondaryTable Annotation"
    • Section 9.1.32 "PrimaryKeyJoinColumn Annotation"


Can you use @SecondaryTable @SecondaryTable annotation problem?

0

精彩评论

暂无评论...
验证码 换一张
取 消