I have the tables as in the screenshot above
Class are written as below
@Entity
public class Object {
@Id
private int id;
private String name;
@OneToMany(mappedBy="object",fetch=FetchType.LAZY)
private List<ObjectAttribute> attrubuteList;
}
@Entity
public class ObjectAttribute {
@Id
private int id;
@Id
@ManyToOne
@JoinColumn(name="objectId")
private Object object;
private String name;
}
@Entity
public class Filter {
@Id
private int filterId;
@ManyToOne
@JoinColumn(name="ObjectId")
private Object object;
private String filterName;
@OneToMany(mappedBy="filter")
private Set<FilterAttribute> filterValues;
}
@Entity
public class FilterAttribute implements Serializable {
@Id
private int filterAttrId;
@Id
@ManyToOne
@JoinColumn(name="objectId")
private Object object;
@Id
@ManyToOne
@JoinColumn(name="filterId")
private Filter filter;
@Id
@ManyToOne
@JoinColumn(name="attributeId")
private ObjectAttribute attribute;
private String value;
}
Note not added getter and setters
and test code as below
List<Object> list = sess.createCriteria(Object.class).list();
for(Object ob: list)
{
System.out.println("Object name : "+ ob.getName());
List<ObjectAttribute> attList = ob.getAttrubuteList();
for (Iterator iterator = attList.iterator(); iterator.hasNext();) {
ObjectAttribute objectAttribute = (ObjectAttribute) iterator
.next();
System.out.println(objectAttribute.getName());
}
}
I am getting the below exception
Caused by: org.hibernate.AnnotationException: A Foreign key refering test.rest.ObjectAttribute from test.rest.FilterAttribute has the wrong number of column. should be 2
at org.hibernate.cfg.annotations.TableBinder.bindFk(TableBinder.java:450)
i came to know i should have the 2 attributes in FilterAttribute class to hold the composite key.. But how can we do that?
@Entity
public class ObjectAttribute {
@Id
private int id;
@Id <------------------------ try to remove this annotation
@ManyToOne
@JoinColumn(name="objectId")
private Object object;
private String name;
}
It thinks your ObjectAttribute has 2 ids compound key
UPDATE: If it really has compound multi column primary key you should reference both columns