When I run the following class:
@Entity
public class SurveyResponse {
@Id
private String assignmentId;
public String getAssignmentId() {
return assignmentId;
}
public void setAssignmentId(String assignmentId) {
this.assignmentId = assignmentId;
}
@ElementCollection
@MapKeyColumn(name="topic")
@Column(name="relevance")
@CollectionTable(name="RelevanceScore", joinColumns=@JoinColumn(name="assignmentId"))
Map<Topic, Relevance> topicRelevance = new HashMap<Topic, Relevance>(); // maps from attribute name to value
public static void main( String[] args ) {
Configuration config = new Configuration();
config.addAnnotatedClass(SurveyResponse.class);
config.configure( "hibernate.cfg.xml" );
new SchemaExport(config).create( true, true );
}
}
it creates the tables SurveyResponse and RelevanceScore as expected. However, when I place the @Id annotation above the getter for the primary key…
@Entity
public class SurveyResponse {
private String assignmentId;
@Id
public String getAssignmentId() {
return assignmentId;
}
...
}
… it fails to produce table RelevanceScore. Why?
Short answer : you have to choose whether you put your annotations on fields or on getters, you cannot mix them.
Long answer : Hibernate looks for the @Id annotation ; if it is on a field, it looks for all other annotations on fields, and doesn’t even bother to look on getters. The opposite also holds true : if the @Id annotation is on a getter, the annotations you put on other fields won’t be taken into account.
This is why your tables aren’t generated if you only move your @Id annotation on the getAssignment method ; you should also put all the annotations that describe the topicRelevance field on its related getter.