alexanoid
alexanoid

Reputation: 25770

Spring Data Neo4j 4, OGM and @Relationship annotation

I have a following base entity:

@NodeEntity
public class Likeable extends Authorable {

    private final static String CONTAINS = "CONTAINS";

    @Relationship(type = CONTAINS, direction = Relationship.INCOMING)
    private Set<Like> likes = new HashSet<>();

    private long totalLikes;

    private long totalDislikes;

    private double likeSum;

    public long getTotalLikes() {
        return totalLikes;
    }

    public void setTotalLikes(long totalLikes) {
        this.totalLikes = totalLikes;
    }

    public long getTotalDislikes() {
        return totalDislikes;
    }

    public void setTotalDislikes(long totalDislikes) {
        this.totalDislikes = totalDislikes;
    }

    public double getLikeSum() {
        return likeSum;
    }

    public void setLikeSum(double likeSum) {
        this.likeSum = likeSum;
    }

}

with a current class everything works fine but when I add likes getter/setter to this class:

public Set<Like> getLikes() {
    return likes;
}

public void setLikes(Set<Like> likes) {
    this.likes = likes;
}

my tests fail with an assertion error(no exceptions).. for example after delete query.

But after adding

@Relationship(type = CONTAINS, direction = Relationship.INCOMING)

over getter/setter everything starts working fine again:

@NodeEntity
public class Likeable extends Authorable {

    private final static String CONTAINS = "CONTAINS";

    @Relationship(type = CONTAINS, direction = Relationship.INCOMING)
    private Set<Like> likes = new HashSet<>();

    private long totalLikes;

    private long totalDislikes;

    private double likeSum;

    @Relationship(type = CONTAINS, direction = Relationship.INCOMING)
    public Set<Like> getLikes() {
        return likes;
    }

    @Relationship(type = CONTAINS, direction = Relationship.INCOMING)
    public void setLikes(Set<Like> likes) {
        this.likes = likes;
    }
...

}

Is it a correctly annotated NodeEntity class ? To me such kind of declaration looks a little bit redundant. Could you please advise what is a correct declaration in this case ?

Upvotes: 0

Views: 479

Answers (1)

František Hartman
František Hartman

Reputation: 15076

Yes, this is the correct way to implement it right now - as of neo4j-ogm version 2.1.x.

See the documentation:

The direction attribute on a @Relationship defaults to OUTGOING. Any fields or methods backed by an INCOMING relationship must be explicitly annotated with an INCOMING direction.

https://neo4j.com/docs/ogm-manual/current/reference/#reference:annotating-entities:relationship (end of the section).

I think you actually don't need the annotation on the field, but you need both setter and getter. Also there is an issue on neo4-ogm github that is related.

Upvotes: 4

Related Questions