简体   繁体   中英

Hibernate column used as a part of a composite primary key and a part composite foreign key at the same time

I got this table structure where we are not allowed to change and i have problems finding an Hibernate mapping solution.

Table A

a1 (pk)
a2

Table B

b1 (pk, fk on 'A.a1')
b2 (pk)
b3

Table C

c1 (pk, fk on 'B.b1')
c2 (pk, fk on 'B.b2')
c3 (pk)
c4

Table D

d1 (pk)
d2 (pk, fk on 'A.a1')
d3 (fk on 'C.c2')
d4 (fk on 'C.c3')
d5

Now the problem i got is on theb level of column d2 of Table D which is a part of composite key and also a part of foreign key on Table C

In Hibernate I did this

@Embeddable
public class TableDId {
    private Long d1;
    private TableA d2;

    @Column(name="d1")
    public Long getD1() {
        return this.d1;
    }

    @ManyToOne
    @JoinColumn(name="d2")
    public Long getD2() {
        return this.d2;
    }
    // Setters
}


@Entity
public class TableD {
    private TableDId id;
    private TableC tableC;

    @EmbeddedId @GeneratedValue(strategy = GenerationType.AUTO)    
    public TableDId getId() {
        return this.id;
    }

    @ManyToOne
    @JoinColumns({
        @JoinColumn(name="id.d2", referencedColumnName="c1"),
        @JoinColumn(name="d3", referencedColumnName="c2"),
        @JoinColumn(name="d4", referencedColumnName="c3")
    })
    public TableC getTableC() {
        return tableC;
    }

    // Setters
}

As you can guess that doesn't work, i got an Hibernate error when saving a new TableD

java.sql.BatchUpdateException: Unknown column 'id.d2' in 'field list'

Can anyone propose a working solution?

Thanx a lot.

@JoinColumn(name="id.d2", referencedColumnName="c1")

Try to remove id. from mapping

@JoinColumn(name="d2", referencedColumnName="c1")

Example http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html/entity.html (section 2.2.6)

You should post all annotated classes. Are you using in all classes @EmbeddedId or do you also use IdClass ? You should have a look at the JPA 2 specification in the "Mapping of Derived Identities" section. I reckon you need to use @MapsId on the association. Or place the @Id annotation on the association as well, but this will depend on how exactly you mapped the other classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM