[My environment: Hibernate v3.2.1 with JBoss AS 4.2.2]
Question: how to correctly annotate the entity class and IdClass for Hibernate when @ManyToOne is part of the composite key?
Following works fine with OpenJPA. However when trying with Hibernate in JBoss, I run into issues (listed after the code).
Code:
@Entity
@Table (name="user")
public class User {
@Id
private long uid;
@OneToMany (mappedBy="user")
private List <UserContact> contacts;
...
}
@Entity
@Table (name="userContact")
@IdClass (UserContact.UserContactId.class)
public class UserContact {
@id
private String name;
@id
@Column (name="userId")
@ManyToOne
private User user;
public static class UserContactId implements Serializable {
public string name;
/* To make it work with OpenJPA, the advise I got on openJPA forum
* was that a) The type "long" must match the type of primary key
* in class User.java and b) The name "user" must match the name
* of the variable in UserContact class.
*/
public long user;
....
}
}
Issues with Hibernate:
1) First issue was that Hibernate was not able to find column name "userid" in table UserContact. This is because I think Hibernate expects annotations inside the IdClass. So I duplicated the annotation "@Column (name="userId")" on the IdClass field "user" to get around that problem.
2) Next problem is while inserting a new row into UserContact table, it gave error about incorrect type for IdClass field "user". There was a mismatch in the code and hibernate about whether the type is "long" or "User class" for this field.
How should IdClass and Entity class be annotated to make them work with Hibernate? Since both OpenJPA and Hibernate implement the EJB3/JPA specs, I would have expected my code to work as-is in Hibernate...