1

Considering the following entity. I intend to have the Child class reference any of the two derived food class ( Local Food or Foreign ). This is an contrived example, my real domain object are much complex, hence combining and using a FoodType column for example is not an option as both Food subclass are similar only in few traits.

@MappedSuperclass
public abstract class Food {

}



@Entity
public class LocalFood extends Food {

private long id;
private String name;
}


@Entity
public class ForeignFood extends Food {

    private long id;
    private String name;
}



@Entity
public class Child {    
private Food food; //Base Class needed here 
@ManyToOne()
public Food getFood() {
    return food;
}
}

Caused by: org.hibernate.AnnotationException: @OneToOne or @ManyToOne on                     com.sample.Child.food references an unknown entity: com.sample.Food

Neither does using inheritance and discriminator.

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract class Food {

private long id; // set , get (Auto gen) 
}

Is it possible to get this kind of mapping to work?

4
  • 1
    You must map the Food class as an entity, with an Inheritance strategy, for this to be possible. What is the exception you get when doing that?
    – JB Nizet
    Jul 16, 2012 at 10:46
  • I get Caused by: java.lang.ClassCastException: org.hibernate.mapping.SingleTableSubclass Caused by: java.lang.ClassCastException: org.hibernate.mapping.JoinedSubclass. For each InheritanceType.
    – lawal
    Jul 16, 2012 at 11:18
  • This is caused by a mapping problem. See forum.hibernate.org/viewtopic.php?f=1&t=1005287 for example. This ID should be declared in the root class (Food). Not in every subclass.
    – JB Nizet
    Jul 16, 2012 at 11:47
  • True, subclasses should not have ID. It works now. Thanks
    – lawal
    Jul 16, 2012 at 13:24

1 Answer 1

2

JB Nizet was right. Now food class looks like this.

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Food {

 private long id;

 public void setId(long id) {
    this.id = id;
 }

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 public long getId() {
    return id;
 }

}

And id removed from subclasses.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.