facewindu
facewindu

Reputation: 725

Two attributes of the same entity

I have two entities

@Entity
class A {
    @Id
    private Long Id;

    //attributes of A
}

@Entity
class B {  
    xxx
    private A instanceOfA_1;

    xxx
    private A instanceOfA_2;
}

As you see, I have two attributes of type A in class B.

How would you annotate these two attributes in Hibernate ? In the end, in the database, I expect to find two columns in the table B, each column containing the key id in table A.

I guess this is a simple ORM question, but I didn't manage to get it alone...


EDIT : after the response above, you suggest that I do the following ?

@Entity
class A {
  @Id
  private Long Id;  
  //attributes of A
}

@Entity
class B {
@ManyToOne
private A instanceOfA_1;
@ManyToOne
private A instanceOfA_2;
}

This will create the following tables ?

Table A
  id
  attributes

Table B
  a_id_1
  a_id_2

How do I specify the name of the columns in table B (i.e. a_id_1 and a_id_2) ?

Upvotes: 0

Views: 1958

Answers (2)

Mikko Maunu
Mikko Maunu

Reputation: 42114

This is rather typical situation, each of them should be annotated with @ManyToOne. @OneToOne should be used if per relation only one B can be related to given A. If database schema is generated from the entities, with @OneToOne there will be unique constraint in foreign key.

@JoinColumn can be used to specify name of the foreign key column:

 @JoinColumn(name="preferred_column_name")

Upvotes: 2

overmeulen
overmeulen

Reputation: 1158

Try this :

@Entity
class A {
   @Id
   private Long Id;  
}

@Entity
class B {
   @ManyToOne
   @JoinColumn(name="A_1")
   private A instanceOfA_1;

   @ManyToOne
   @JoinColumn(name="A_2")
   private A instanceOfA_2;
}

Upvotes: 1

Related Questions