18

Say, I have following entities:

@Entity
public class A {
  @Id
  @GeneratedValue
  private Long id;

  @Embedded
  private B b;

  //getters and setters
}

@Embeddable
public class B {
  @OneToMany
  private List<C> cList;
  //getters and setters
}

@Entity
public class C {
  @Id
  @GeneratedValue
  private Long id;
  //other fields, getters and setters
}

Using schema-autogeneration feature with Hibernate I get an additional table which contains mappings between A and C. But I'd like to implement a one-to-many relationship by adding A's id into C (e.g without additional table).

Is this possible? If yes, what annotations should I use to create such a mapping?

jFrenetic
  • 5,384
  • 5
  • 42
  • 67

1 Answers1

15

In general that is possible with @JoinColumn annotation. It works also with embeddables.

@OneToMany
@JoinColumn(name="A_ID")
private List<C> cList;

If you are not happy with A_ID name for column given in embeddable, you can override column name in entity A:

@AssociationOverride(name= "cList",
        joinColumns = @JoinColumn(name="SOME_NAME_FOR_JOIN_COLUMN_IN_TABLE_C"))
@Embedded
private B b;
Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135
  • But how do I specify, that `A_ID` is the identifier of entity `A`? – jFrenetic Mar 26 '12 at 19:09
  • You do not have to specify that, mappings given in B are evaluated in the context of A and that's why your persistence provider knows it. Or maybe you mean how to override join column name - I added example to answer. – Mikko Maunu Mar 26 '12 at 19:31
  • Thanks a lot! That worked for me. I thought I needed to explicitly tell the persistence provider what entity to get the `id` from, but it turned out to be a little smarter :) – jFrenetic Mar 26 '12 at 19:59