Tmss G-ils
Tmss G-ils

Reputation: 153

Hibernate: query entity's field from two possible places?

Is it possible to fetch entity's field from 2 possible tables?

For example:

   @Entity
   @Table(name = "TABLE_A")
   public class A{

     @Id
     @Column(name = "ID")
     @GeneratedValue(strategy = GenerationType.AUTO)
     private Long id;
   }

   @Entity
   @Table(name = "TABLE_B")
   public class B{

     @Id
     @Column(name = "ID")
     @GeneratedValue(strategy = GenerationType.AUTO)
     private Long id;
   }

@Entity
@Table(name = "TABLE_PARENT")
public class PARENT{

  // This field needs to be fetched from A table or from B table!!! by some
  // conditions
  @OneToOne
  @JoinColumn(name = "A_B_ID")
  private A a;                     
}

a field in Parent class needs to be fetched from table_A or table_b according to some condition!

Any idea will be appreciated!

Clarification: if the Parent actually points to B instance i wan't to fetch instance of B! Table per class inheritance only looks in A's table because we specified in the Parent class that the field his of A type!?

Do you have other ideas?

Upvotes: 0

Views: 131

Answers (2)

Francisco Spaeth
Francisco Spaeth

Reputation: 23913

One solution would be inherit A and B from a common class, for instance C and refer C in Parent class. A draft could be:

@MappedSuperclass
public class AB {
    @Id
    private Integer id;
...
}

@Entity
public class A extends AB {
...
}

@Entity
public class B extends AB {
...
}

@Entity
public class Parent {
    ...
    @Id
    private Integer id;
    @OneToOne
    private AB ab;
}

documentation section 2.2.4.1

Upvotes: 1

dursun
dursun

Reputation: 1846

you can achieve this by using hibernate inheritance functionality; here is an example; http://viralpatel.net/blogs/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping/

Upvotes: 1

Related Questions