So far, the website had only been a plain old movie database (POMD?). We now wanted to add a touch of social to it.
So we started out by taking the User class that we'd already coded and made it a full-fledged Spring Data Neo4j entity. We added the ability to make friends and to rate movies. With that we also added a simple UserRepository that was able to look up users by ID.
Example 12.1. Social entities
@NodeEntity class User { @Indexed String login; String name; String password; @RelatedToVia(elementClass = Rating.class, type = RATED) Iterable<Rating> ratings; @RelatedTo(elementClass = User.class, type = "FRIEND", direction=Direction.BOTH) Set<User> friends; public Rating rate(Movie movie, int stars, String comment) { return relateTo(movie, Rating.class, "RATED").rate(stars, comment); } public void befriend(User user) { this.friends.add(user); } } @RelationshipEntity class Rating { @StartNode User user; @EndNode Movie movie; int stars; String comment; public Rating rate(int stars, String comment) { this.stars = stars; this.comment = comment; return this; } }
We extended the DatabasePopulator to add some users and ratings to the initial setup.
Example 12.2. Populate users and ratings
@Transactional public List<Movie> populateDatabase() { Actor tomHanks = new Actor("1", "Tom Hanks").persist(); Movie forestGump = new Movie("1", "Forrest Gump").persist(); tomHanks.playedIn(forestGump, "Forrest"); User me = new User("micha", "Micha", "password", User.Roles.ROLE_ADMIN, User.Roles.ROLE_USER).persist(); Rating awesome = me.rate(forestGump, 5, "Awesome"); User ollie = new User("ollie", "Olliver", "password", User.Roles.ROLE_USER).persist(); ollie.rate(forestGump, 2, "ok"); me.addFriend(ollie); return asList(forestGump); }
We also put a ratings field into the Movie class to be able to get a movie's ratings, and also a method to average its star rating.
Example 12.3. Getting the rating of a movie
class Movie { ... @RelatedToVia(elementClass=Rating.class, type="RATED", direction = Direction.INCOMING) Iterable<Rating> ratings; public int getStars() { int stars = 0, count = 0; for (Rating rating : ratings) { stars += rating.getStars(); count++; } return count == 0 ? 0 : stars / count; } }
Fortunately our tests highlighted the division by zero error when calculating the stars for a movie without ratings. The next steps were to add this information to the movie presentation in the UI, and creating a user profile page. But for that to happen, users must first be able to log in.