3

My issue is that I have a Spring model

@Entity
public class PetOwner {
    @ManyToOne
    @JoinColumn(name = "pet_id", nullable = true)
    private Pet pet;

with Pet being an abstract class with 2 subclasses Dog and Cat.

@Entity
@Inheritance(strategy= InheritanceType.JOINED)
public abstract class Pet {
    @OneToMany(fetch = FetchType.LAZY)
    protected Set<PetOwner> owners;
}

@Entity
public class Cat extends Pet 

@Entity
public class Dog extends Pet 

When I create a new PetOwner in a Struts-form and try to bind its pet to either a Dog or Cat object, I get an error on submitting the form:

Error creating bean with name 'de.model.Pet': Instantiation of bean failed; 
nested exception is org.springframework.beans.BeanInstantiationException: 
Could not instantiate bean class [de.model.Pet]: Is it an abstract class?; 
nested exception is java.lang.InstantiationException

How can I tell Spring to initialize the de.model.Dog or de.model.Cat based on the class pet-object?

FYI: I have a PetDAO and PetService, but I am not sure whether they influence this problem.

I appreciate every help!

2
  • My issue is that I have a Spring model. But I don't see how Spring is involved here. Commented Nov 17, 2014 at 21:51
  • Could this help you stackoverflow.com/questions/8119678/… Commented Nov 18, 2014 at 1:19

1 Answer 1

1

Personally, I would turn Pet to an Interface and make Cat and Dog implement it to avoid this kind of problems. Sorry for off-topic!

Anyhow, if you want some member of your class to be dynamically initialized\populated, try the Lookup Method Injection. Read pp. 3.3.4.1 here.

If the class that contains the dynamic member was created in scope=singletone (the default for spring bean container) every time you will access the field that has a lookup method assigned, you will get an appropriate object according to the business logic implemented inside the lookup method.

Also, I found this example in Spring documentation - I think it is very clear. Take a look at "3.4.6.1 Lookup method injection"

When you configure the PetOwner class assign a lookup method to its Pet member - it will be called whenever you need a new instance of the Pet bean.

Good luck!

Sign up to request clarification or add additional context in comments.

1 Comment

I used an AbstractClass because I want to create a bidirectional mapping between 'Pet' and #PetOwner', which - I have to admit - I did not point out in the snippet above earlier. As far as my understanding goes, I would have to use a @ManyToAny relation from PetOwner to Pet, which cannot be bidirectional.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.