Create The Restaurant Entity
Now that we have created all our supporting entities, we'll bring them together to create the main Restaurant entity, which will serve as the central model for our restaurant review platform.
Creating the Restaurant Class
The Restaurant entity ties together all the components we need to represent a restaurant in our system.
Let's create a new class in the com.devtiro.restaurant.domain.entities package:
package com.devtiro.restaurant.domain.entities;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.annotations.GeoPointField;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import java.util.ArrayList;
import java.util.List;
@Document(indexName = "restaurants")
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Restaurant {
// Class implementation will go here
}Defining the Document and Fields
The @Document annotation marks this class as an Elasticsearch document and specifies the index name as "restaurants".
Let's add our fields:
@Id
private String id;
@Field(type = FieldType.Text)
private String name;
@Field(type = FieldType.Text)
private String cuisineType;
@Field(type = FieldType.Keyword)
private String contactInformation;
@Field(type = FieldType.Float)
private Float averageRating;
@GeoPointField
private GeoPoint geoLocation;The geoLocation field uses the @GeoPointField annotation to store the restaurant's location as a point on a map.
Adding Nested Relationships
We'll now integrate the entities we created in previous lessons:
@Field(type = FieldType.Nested)
private Address address;
@Field(type = FieldType.Nested)
private OperatingHours operatingHours;
@Field(type = FieldType.Nested)
private List<Photo> photos = new ArrayList<>();
@Field(type = FieldType.Nested)
private List<Review> reviews = new ArrayList<>();
@Field(type = FieldType.Nested)
private User createdBy;We use FieldType.Nested to maintain the relationship structure between the Restaurant and its related entities.
The photos and reviews lists are initialized with empty ArrayList objects to prevent null pointer exceptions.
Summary
- Created the
Restaurantentity with@Documentconfiguration for Elasticsearch - Added basic fields including
name,cuisineType, andcontactInformation - Integrated
@GeoPointFieldfor storing restaurant location data - Added nested relationships to
Address,OperatingHours,Photo,Review, andUser