Question

How do we associate class A with class B when class A has a primary key id1 and class B has a composite key made of id1 and id2.

Code will look like this:

@Entity
@Indexed
public class ClassA {

    @Id
    @DocumentId
    private Integer id1;

    @Field
    private Integer description;

    @ManyToOne(cascade = {CascadeType.ALL})
    @IndexEmbedded
    ClassB b;

    // getters and setters

}


@Entity
public class ClassB {

    @EmbdeddedId
    @DocumentId
    private ClassB_Pk id;
}

@Embeddable
public class ClassB_Pk {

    private Integer id1;
    private Integer id2;

    // getters and setters

}

Solution Approach1:

public class classA {

    @ManyToOne(cascade = { CascadeType.ALL})
    @IndexedEmbedded
    @JoinColumn(name="id1")
    private ClassB b;

}

Error Received: Student_Main has the wrong number of column. should be 2

Solution Approach2:

public class classA {

    @ManyToOne(cascade = { CascadeType.ALL})
    @IndexedEmbedded
    @MapsId("id1")
    private ClassB b;

}

Error: No errors thrown, but no indexing occured (as checked with luke)

I have stumbled upon this problem for quite a while. Any recommendation will be greatly appreciated.

Thank you in advance

Was it helpful?

Solution

The problem is solved. Actually, there was an OneToMany relation from Class A to Class B. I changed the relation between those classes and put "JoinColumn" annotation on both of them. Code looks like below:

@Entity
@Indexed
public class ClassA {
    @Id
    @DocumentId
    private Integer id1;

    @Field
    private Integer description;

    @OneToMany(fetch=FetchType.EAGER, cascade = {CascadeType.ALL})
    @IndexEmbedded
    @JoinColumn(name="id1", referencedColumn="id1", updatable = false, insertable = false)
    Set<ClassB> b;

    // getters and setters

}

@Entity
public class ClassB {
    @EmbeddedId
    @DocumentId
    private ClassB_Pk id;

    @ContainedIn
    @ManyToOne(fetch=FetchType.EAGER, cascade = {CascadeType.ALL})
    @JoinColumn(name="id2", referencedColumnName="id2", insertable=false, updatable=false)
    ClassA a;


// other properties
// setters and getters

}

@Embeddable
public class ClassB_Pk {
    private Integer id1;
    private Integer id2;

    // getters and setters

}

Hope this helps to anybody who got stumbled upon on similar situation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top