Spring Data Neo4J: Requested a entity of type ‘X’, but the entity is of type ‘Y’

PROBLEM

Let’s assume we have a node entity like this:-

@NodeEntity
public final class Person {
    @GraphId
    private Long id;

    private String name;

    @Fetch
    @RelatedTo(type = "likes", direction = OUTGOING)
    public Set<Restaurant> likesRestaurants;

    @Fetch
    @RelatedTo(type = "likes", direction = OUTGOING)
    public Set<Beverage> likesBeverages;

    public Person() {
    }

    public Person(final String name,
                  final Set<Restaurant> likesRestaurants,
                  final Set<Beverage> likesBeverages) {
        this.name = name;
        this.likesRestaurants = likesRestaurants;
        this.likesBeverages = likesBeverages;
    }
}

When saving this entity, we get this exception:-

Exception in thread "main" org.springframework.data.neo4j.mapping.PersistentEntityConversionException: 
Requested a entity of type 'class myproject.Restaurant', 
but the entity is of type 'class myproject.Beverage'.

SOLUTION

This problem occurs because relationship likes is being used by both Restaurant entity and Beverage entity.

To fix it, we need to enforce the target type.

@NodeEntity
public final class Person {
    @GraphId
    private Long id;

    private String name;

    @Fetch
    @RelatedTo(type = "likes", direction = OUTGOING, enforceTargetType = true)
    public Set<Restaurant> likesRestaurants;

    @Fetch
    @RelatedTo(type = "likes", direction = OUTGOING, enforceTargetType = true)
    public Set<Beverage> likesBeverages;

    public Person() {
    }

    public Person(final String name,
                  final Set<Restaurant> likesRestaurants,
                  final Set<Beverage> likesBeverages) {
        this.name = name;
        this.likesRestaurants = likesRestaurants;
        this.likesBeverages = likesBeverages;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s