1

I'm using JPA 2.0 and Hibernate in my project. I have a complex scenario.

Class A and class C correspond to two DB tables and are linked by an 1:N relationship. In the object model, however, between these two classes, there's a third class B that isn't an Entity (it is an util/helper class) and so this helper class has not a corresponding table in the database.

My object model:

@Entity
public class A {
  @Id
  ... id;

  private B b;
}

public class B {
  private List<C> c;
}

@Entity
public class C {
  ...
}

So, I want to know how is it possible to handle such situations?

Tobias Liefke
  • 8,637
  • 2
  • 41
  • 58
Fra83
  • 511
  • 1
  • 5
  • 15

1 Answers1

2

You can use an Embeddable:

@Entity
public class A {
  @Id
  ... id;

  @Embedded
  private B b;
}

@Embeddable
public class B {
  @OneToMany
  private List<C> c;
}

@Entity
public class C {
  ...
}
Tobias Liefke
  • 8,637
  • 2
  • 41
  • 58
  • Thanks Tobias. In class B I have an attribute like this: **private Map attributes= new LinkedHashMap()**. So I annotate this attribute like this: **@OneToMany @MapKey(name="id")** where 'id' is primary key of C. So, when I persist A, I have the following error: **ora-00972 identifier is too long**; because hibernate generate a query like this: **insert into A_C (A_ID, attributes_C_ID) values (?, ?)**. Actually A and C are longer than these (38 characters) anche this is the problem. I'm doing in the right way or am I doing something wrong? – Fra83 Nov 04 '15 at 11:37
  • The thing I don't understand is why hibernate try to run this query? I don't have A_C table in my DB. I have A id in C table and stop. – Fra83 Nov 04 '15 at 11:59
  • Unfortunately this question differs from you first one - and it is difficult to discuss that in the comments section. Can you create a new question with all relevant information? You can then add the link to your new question here. – Tobias Liefke Nov 04 '15 at 12:39
  • Thanks Tobias. For now, your solution is perfect.For now the problem I was talking about does not exist, but I could take the following http://stackoverflow.com/questions/9878066/embeddable-entity-with-onetomany-attribute but the solution was not good for me. If I want to persist A with all children of type C, how do I annotate classes? – Fra83 Nov 05 '15 at 10:08
  • Again a new question, but anyway: You should use `@OneToMany(cascade=CascadeType.PERSIST)` or `@OneToMany(cascade=CascadeType.ALL)`. It helps to read the JPA documentation (especially to check all annotations with their attributes). – Tobias Liefke Nov 05 '15 at 10:25