Quantcast
Viewing all articles
Browse latest Browse all 76

JoinTable with two keys primary keys from different tables

Hello everyone.

Lest pretend I have:

Table A with A Entity

Code:

@Entity
@Column(name="A")
public class A{

@ManyToMany
@Cascade(org.hibernate.annotations.CascadeType.ALL)
@JoinTable(name="C",
                joinColumns=@JoinColumn(name="A_ID"),
                inverseJoinColumns=@JoinColumn(name="B_ID"))
public B b;

//set and get methods

}

Table B with B Entity

Code:

@Entity
    @Column(name="B")
    public class B{

    @ManyToMany
    @Cascade(org.hibernate.annotations.CascadeType.ALL)
    @JoinTable(name="C",
                joinColumns=@JoinColumn(name="B_ID"),
                inverseJoinColumns=@JoinColumn(name="A_ID"))
    public A a;

    //set and get methods

    }

JoinTable C between A and B which contain FK on A and B tables also.

So on, I also will have the table and Entity class the name for examle Alphabet:

Code:

  @Entity
    @Column(name="Alphabet")
    public class Alphabet{

    private Data anydata;

    //set and get methods

    }

So Between class Alphabet and A Entity and B Entity I will have an Undirectional, JoinTable, OneToMany relationships.That's mean that Classes A and B will know about Alphabet class, but Alphabet will not know about A and B. When I will try to enset data to my database from A side to class B and class Alphabet I will have an exception like this:

Quote:

Hibernate: insert into C (A_ID, Alphabet_ID) values (?, ?) ERROR: org.hibernate.util.JDBCExceptionReporter - Field 'B_ID' doesn't have a default value ERROR: org.hibernate.event.def.AbstractFlushingEventListe ner - Could not synchronize database state with session
If I will do this from B side I will have an error like this:

Quote:

Hibernate: insert into C (B_ID, Alphabet_ID) values (?, ?) ERROR: org.hibernate.util.JDBCExceptionReporter - Field 'A_ID' doesn't have a default value ERROR: org.hibernate.event.def.AbstractFlushingEventListe ner - Could not synchronize database state with session
That's meant that some of my foreign keys an JoinTable C did not get an ID because I'm inserting it from side which is can not to generate or insert data to this jointable C, I don't know why? If I will add to my JoinTable database schema for some of my foreign key like A_ID or B_ID the DEFAULT "number" than it is works, it's inser data, but it will always insert the same Number by DEFAULT which I put in "number". But What I want, is to give for one of my problem foreign key's in joinTable C the same value as in parient table A or B!!! Maybe I can use some of the @Generator annotation from Hibernate for my JoinTable in my Entity class.

Thank you.

Viewing all articles
Browse latest Browse all 76

Trending Articles