SJuan76
SJuan76

Reputation: 24780

Cannot use an @IdClass attribute for a @ManyToOne relationship

I have a Gfh_i18n entity, with a composite key (@IdClass):

@Entity @IdClass(es.caib.gesma.petcom.data.entity.id.Gfh_i18n_id.class)
public class Gfh_i18n implements Serializable {

  @Id @Column(length=10, nullable = false)
  private String localeId = null;

  @Id <-- This is the attribute causing issues
  private Gfh gfh = null;
  ....
}

And the id class

public class Gfh_i18n_id implements Serializable {
  private String localeId = null;
  private Gfh gfh = null;
  ...
}

As this is written, this works. The issue is that I also have a Gfh class which will have a @OneToMany relationship to Gfh_i18n:

@OneToMany(mappedBy="gfh")
@MapKey(name="localeId")
private Map<String, Gfh_i18n> descriptions = null;

Using Eclipse Dali, this gives me the following error:

 In attribute 'descriptions', the "mapped by" attribute 'gfh' has an invalid mapping type for this relationship.

If I just try to do, in Gfh_1i8n

@Id @ManyToOne
private Gfh gfh = null;

it solves the previous error but gives one in Gfh_i18n, stating that

The attribute matching the ID class attribute gfh does not have the correct type es.caib.gesma.petcom.data.entity.Gfh

This question is similar to mine, but I do not fully understand why I should be using @EmbeddedId (or if there is some way to use @IdClass with @ManyToOne).

I am using JPA 2.0 over Hibernate (JBoss 6.1)

Any ideas? Thanks in advance.

Upvotes: 2

Views: 9474

Answers (1)

Brian Vosburgh
Brian Vosburgh

Reputation: 3276

You are dealing with a "derived identity" (described in the JPA 2.0 spec, section 2.4.1).

You need to change your ID class so the field corresponding to the "parent" entity field in the "child" entity (in your case gfh) has a type that corresponds to either the "parent" entity's single @Id field (e.g. String) or, if the "parent" entity uses an IdClass, the IdClass (e.g. Gfh_id).

In Gfh_1i8n, you should declare gfh like this:

@Id @ManyToOne
private Gfh gfh = null;

Assuming GFH has a single @Id field of type String, your ID class should look like this:

public class Gfh_i18n_id implements Serializable {
  private String localeId = null;
  private String gfh = null;
  ...
}

Upvotes: 7

Related Questions