Neo4j Springboot SpringData restful example not complete without relationship entity - rest

I am using the springio accessing-neo4j-data-rest example which has the relationship as part of the Person class and really doesn't show the advantage of Neo4j. I tried creating a Family relationship entity, but can't create a relationship using a restful service with Springboot and port 8080.
My service works and creates the relationship using http://localhost:7474/db/data/node/67/relationships
Shouldn't I be able to do this (where 66 and 67 are existing Person entities):
POST to http://localhost:8080/people/67/family
{
"to" : "http://localhost:8080/people/66",
"type" : "RELATED_TO"
}
I get the error:
{
"timestamp": 1486948326367,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/people/67/family"
}
Person.java
package hello;
import java.util.HashSet;
import java.util.Set;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
#NodeEntity
public class Person {
#GraphId public Long id;
private String firstName;
private String lastName;
#Relationship(type = Family.TYPE, direction = Relationship.UNDIRECTED)
private Set<Family> family = new HashSet<Family>();
public Long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Set<Family> getFamily() {
return family;
}
public void addFamily(Family f) {
family.add(f);
}
public void addFamily(Person target, String association) {
this.family.add(new Family(this, target, association));
}
public void addFamily(Person target) {
this.family.add(new Family(this, target));
}
}
Family.java
package hello;
import org.neo4j.ogm.annotation.EndNode;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.Property;
import org.neo4j.ogm.annotation.RelationshipEntity;
import org.neo4j.ogm.annotation.StartNode;
#RelationshipEntity(type = Family.TYPE)
public class Family {
public static final String TYPE = "RELATED_TO";
#GraphId
private Long id;
#Property
private String association;
#StartNode
private Person p1;
#EndNode
private Person p2;
public Family() {
}
public Family(Person first, Person second) {
this.p1 = first;
this.p2 = second;
}
public Family(Person first, Person second, String assoc) {
this.p1 = first;
this.p2 = second;
association = assoc;
}
public Long getId() {
return id;
}
public Person getFirst() {
return p1;
}
public Person getSecond() {
return p2;
}
public String getAssociation() {
return association;
}
public void setAssociation(String association) {
this.association = association;
}
}
PersonRepository.java
package hello;
import java.util.List;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
#RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {
List<Person> findByLastName(#Param("name") String name);
List<Person> findByFirstName(#Param("name") String name);
}
FamilyRepository .java
package hello;
import org.springframework.data.neo4j.repository.GraphRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
#RepositoryRestResource(collectionResourceRel = "family", path = "family") // what should go here????
public interface FamilyRepository extends GraphRepository<Family> {
// //creates a get - need a post
// #Query("MATCH (a:Traveler),(b:Traveler) WHERE a.lastName = {from} AND b.lastName = {to} CREATE (a)-[r:RELATED_TO]->(b) RETURN r")
// void worksWith(#Param("to") String to);
}
Edited:2-19-2017 - Getting closer. I needed a controller - something like this:
#RestController
public class FamilyController {
...
#RequestMapping(value = "/people/{id}/family", method = RequestMethod.POST, consumes = APPLICATION_JSON, produces = APPLICATION_JSON)
#ResponseStatus(value = HttpStatus.ACCEPTED)
#ResponseBody
Family addFamily(#RequestBody Family f, #PathVariable(value = "id") String id) {

Related

how to save subset data of one collection in another collection in SpringBoot Mongo DB

I have 1 collection namely profile now since it has lots of properties and since in future I will be needing more properties i decided to add new data in new collection namely profile_details .I will be keeping 1 field in profile_details namely profileId whose value will be same as primary key of collection profile.
I will be saving data of profile in profile collection using profileRepository.save(profile)
In order to save data in profile_details collection I am using aggregation pipeline in order to save data of profile_details collection but $out operator replaces documents instead of inserting new documents.Below is my sample code.Any help will be deeply appreciated
Profile.java
import java.io.Serializable;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.juv.common.bean.model.RecentHealthMetricData;
import com.juv.common.enums.CurrentLanding;
import com.juv.common.enums.MFAPreference;
import com.juv.common.enums.Status;
import com.juv.common.primary.bean.model.Answer;
import com.juv.common.primary.bean.model.DeviceIntegrations;
import com.juv.common.primary.bean.model.DeviceToken;
#Document(collection = "profile")
#JsonIgnoreProperties(ignoreUnknown = true)
#Component
public class Profile extends ProfileDetails implements Serializable {
/**
*
*/
private static final long serialVersionUID = 6608898578832145751L;
#Id
private String profileId;
#Field("kibo_user_id")
#JsonProperty("kibo_user_id")
private String kiboUserId;
#Field("new_recommendations")
#JsonProperty("new_recommendations")
private List<String> newRecommendations;
#Field("kibo_id")
#JsonProperty("kibo_id")
private String kiboId;
#Field("original_kibo_id")
#JsonProperty("original_kibo_id")
private String originalKiboId;
#Field("email")
#JsonProperty("email")
private String email;
#Field("country")
#JsonProperty("country")
private String country;
#Field("first_name")
#JsonProperty("first_name")
private String firstName;
#Field("last_name")
#JsonProperty("last_name")
private String lastName;
#CreatedDate
#Field("created_date")
#JsonProperty("created_date")
private Date createdDate;
#Field("registration_date")
#JsonProperty("registration_date")
private Date registrationDate;
#LastModifiedDate
#Field("last_modified")
#JsonProperty("last_modified")
private Date lastModified;
#Field("phi_mapping_id")
#JsonProperty("phi_mapping_id")
private String phiMappingId;
#Field("phone_number")
#JsonProperty("phone_number")
private String phoneNumber;
#Field("origin")
#JsonProperty("origin")
private String origin;
#Field("gender")
#JsonProperty("gender")
private String gender;
#Field("status")
#JsonProperty("status")
private Status status;
#Field("current_landing")
#JsonProperty("current_landing")
private CurrentLanding currentLanding;
#Field("mfa_preference")
#JsonProperty("mfa_preference")
private MFAPreference mfaPreference;
#Field("profile_recommendation_info_id")
#JsonProperty("profile_recommendation_info_id")
private String profileRecommendationInfoId;
#Field("oldest_profile_recommendation_info_id")
#JsonProperty("oldest_profile_recommendation_info_id")
private String oldestProfileRecommendationInfoId;
#Field("last_question")
#JsonProperty("last_question")
private String lastQuestion;
#Field("answers")
#JsonProperty("answers")
private Answer[] answers;
#Field("is_account_locked")
#JsonProperty("is_account_locked")
private boolean isAccountLocked;
#Field("device_integrations")
#JsonProperty("device_integrations")
private DeviceIntegrations deviceIntegrations ;
#Field("profile_photo")
#JsonProperty("profile_photo")
private String profilePhoto;
#Field("device_token_list")
#JsonProperty("device_token_list")
private List<DeviceToken> deviceTokenList;
#Field("unit_map")
#JsonProperty("unit_map")
private Map<String,String> unitMap;
#Field("recent_health_metric_values")
#JsonProperty("recent_health_metric_values")
private Map<String,RecentHealthMetricData> recentHealthMetricValues;
#Field("last_recommendation_info_date")
#JsonProperty("last_recommendation_info_date")
private Date lastRecommendationInfoDate;
#Field("terms_conditions")
#JsonProperty("terms_conditions")
private boolean termsConditions;
#Field("health_metric_preferences")
#JsonProperty("health_metric_preferences")
private Map<String, String> healthMetricPreferences;
#Field("device_preferences")
#JsonProperty("device_preferences")
private Map<Integer, String> devicePreferences;
#Field("pinpoint_custom_atributes")
#JsonProperty("pinpoint_custom_atributes")
private Map<String,String> pinpointCustomAttributes;
#Field("opt_juvlab_customer")
#JsonProperty("opt_juvlab_customer")
private boolean optJuvLabsCustomer;
#Field("deleted")
#JsonProperty("deleted")
private boolean deleted;
#Field("deleted_timestamp")
#JsonProperty("deleted_timestamp")
private Instant deletedTimestamp;
#Field("daily_action_count_clevertap")
#JsonProperty("daily_action_count_clevertap")
private int dailyActionCountClevertap;
public String getProfileId() {
return profileId;
}
public void setProfileId(String profileId) {
this.profileId = profileId;
}
public String getKiboUserId() {
return kiboUserId;
}
public void setKiboUserId(String kiboUserId) {
this.kiboUserId = kiboUserId;
}
public String getKiboId() {
return kiboId;
}
public void setKiboId(String kiboId) {
this.kiboId = kiboId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
if (email != null) {
email = email.toLowerCase();
}
this.email = email;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public Date getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(Date registrationDate) {
this.registrationDate = registrationDate;
}
public Date getLastModified() {
return lastModified;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
public String getPhiMappingId() {
return phiMappingId;
}
public void setPhiMappingId(String phiMappingId) {
this.phiMappingId = phiMappingId;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getOrigin() {
return origin;
}
public void setOrigin(String origin) {
this.origin = origin;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public CurrentLanding getCurrentLanding() {
return currentLanding;
}
public void setCurrentLanding(CurrentLanding currentLanding) {
this.currentLanding = currentLanding;
}
public MFAPreference getMfaPreference() {
return mfaPreference;
}
public void setMfaPreference(MFAPreference otpPreference) {
this.mfaPreference = otpPreference;
}
public String getProfileRecommendationInfoId() {
return profileRecommendationInfoId;
}
public void setProfileRecommendationInfoId(String profileRecommendationInfoId) {
this.profileRecommendationInfoId = profileRecommendationInfoId;
}
public String getLastQuestion() {
return lastQuestion;
}
public void setLastQuestion(String lastQuestion) {
this.lastQuestion = lastQuestion;
}
public Answer[] getAnswers() {
return answers;
}
public void setAnswers(Answer[] answers) {
this.answers = answers;
}
public boolean isAccountLocked() {
return isAccountLocked;
}
public void setAccountLocked(boolean isAccountLocked) {
this.isAccountLocked = isAccountLocked;
}
public enum ORIGIN {
APP,
KIBO,
SHOPIFY
}
public String getProfilePhoto() {
return profilePhoto;
}
public void setProfilePhoto(String profilePhoto) {
this.profilePhoto = profilePhoto;
}
public DeviceIntegrations getDeviceIntegrations() {
return deviceIntegrations;
}
public void setDeviceIntegrations(DeviceIntegrations deviceIntegrations) {
this.deviceIntegrations = deviceIntegrations;
}
public List<DeviceToken> getDeviceTokenList() {
return deviceTokenList;
}
public void setDeviceTokenList(List<DeviceToken> deviceTokenList) {
this.deviceTokenList = deviceTokenList;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Map<String, String> getUnitMap() {
return unitMap;
}
public void setUnitMap(Map<String, String> unitMap) {
this.unitMap = unitMap;
}
public Date getLastRecommendationInfoDate() {
return lastRecommendationInfoDate;
}
public void setLastRecommendationInfoDate(Date lastRecommendationInfoDate) {
this.lastRecommendationInfoDate = lastRecommendationInfoDate;
}
public boolean isTermsConditions() {
return termsConditions;
}
public void setTermsConditions(boolean termsConditions) {
this.termsConditions = termsConditions;
}
public Map<String, String> getHealthMetricPreferences() {
return healthMetricPreferences;
}
public void setHealthMetricPreferences(Map<String, String> healthMetricPreferences) {
this.healthMetricPreferences = healthMetricPreferences;
}
public Map<String, String> getPinpointCustomAttributes() {
return pinpointCustomAttributes;
}
public void setPinpointCustomAttributes(Map<String, String> pinpointCustomAttributes) {
this.pinpointCustomAttributes = pinpointCustomAttributes;
}
public Map<Integer, String> getDevicePreferences() {
return devicePreferences;
}
public void setDevicePreferences(Map<Integer, String> devicePreferences) {
this.devicePreferences = devicePreferences;
}
public Map<String, RecentHealthMetricData> getRecentHealthMetricValues() {
if(recentHealthMetricValues==null) {
recentHealthMetricValues = new HashMap<>();
}
return recentHealthMetricValues;
}
public void setRecentHealthMetricValues(Map<String, RecentHealthMetricData> recentHealthMetricValues) {
this.recentHealthMetricValues = recentHealthMetricValues;
}
public List<String> getNewRecommendations() {
return newRecommendations;
}
public void setNewRecommendations(List<String> newRecommendations) {
this.newRecommendations = newRecommendations;
}
public boolean isOptJuvLabsCustomer() {
return optJuvLabsCustomer;
}
public void setOptJuvLabsCustomer(boolean optJuvLabsCustomer) {
this.optJuvLabsCustomer = optJuvLabsCustomer;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public Instant getDeletedTimestamp() {
return deletedTimestamp;
}
public void setDeletedTimestamp(Instant deletedTimestamp) {
this.deletedTimestamp = deletedTimestamp;
}
public String getOriginalKiboId() {
return originalKiboId;
}
public void setOriginalKiboId(String originalKiboId) {
this.originalKiboId = originalKiboId;
}
public String getOldestProfileRecommendationInfoId() {
return oldestProfileRecommendationInfoId;
}
public void setOldestProfileRecommendationInfoId(String oldestProfileRecommendationInfoId) {
this.oldestProfileRecommendationInfoId = oldestProfileRecommendationInfoId;
}
public int getDailyActionCountClevertap() {
return dailyActionCountClevertap;
}
public void setDailyActionCountClevertap(int dailyActionCountClevertap) {
this.dailyActionCountClevertap = dailyActionCountClevertap;
}
}
ProfileDetails.java
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import com.fasterxml.jackson.annotation.JsonProperty;
#Document(collection = "profile_details")
public class ProfileDetails {
#Field("profile_id")
private String profileId;
#Field("partner_code")
#JsonProperty("partner_code")
private String partnerCode;
public String getProfileId() {
return profileId;
}
public void setProfileId(String profileId) {
this.profileId = profileId;
}
public String getPartnerCode() {
return partnerCode;
}
public void setPartnerCode(String partnerCode) {
this.partnerCode = partnerCode;
}
}
ProfileFragmentRepositoryImpl.java
package com.juv.common.secondary.repository.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.AddFieldsOperation;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOptions;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.ArrayOperators.ArrayElemAt;
import org.springframework.data.mongodb.core.aggregation.LimitOperation;
import org.springframework.data.mongodb.core.aggregation.LookupOperation;
import org.springframework.data.mongodb.core.aggregation.MatchOperation;
import org.springframework.data.mongodb.core.aggregation.OutOperation;
import org.springframework.data.mongodb.core.aggregation.SetOperation;
import org.springframework.data.mongodb.core.aggregation.SortOperation;
import org.springframework.data.mongodb.core.aggregation.UnsetOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Component;
import com.juv.common.constants.CommonConstants;
import com.juv.common.secondary.dao.Profile;
import com.juv.common.secondary.dao.ProfileDetails;
import com.juv.common.secondary.repository.ProfileFragmentRepository;
import com.juv.common.secondary.repository.ProfileRepository;
import com.mongodb.internal.operation.InsertOperation;
#Component
public class ProfileFragmentRepositoryImpl implements ProfileFragmentRepository {
#Autowired
private MongoTemplate secondaryMongoTemplate;
#Autowired
private ProfileRepository profileRepository;
#Override
public void saveProfileDetails(Profile profile) {
MatchOperation filterOnProfileId = Aggregation.match(Criteria.where("profileId").is(profile.getProfileId()));
SetOperation setProfileId = SetOperation.set("profileId").toValue(profile.getProfileId());
SetOperation setPartnerCode = SetOperation.set("partnerCode").toValue(profile.getPartnerCode());
OutOperation outOperation = new OutOperation("profile_details").uniqueKey("profileId").insertDocuments();
Aggregation aggregation = Aggregation.newAggregation(filterOnProfileId,setProfileId,setPartnerCode,outOperation);
System.out.println("------------------------"+aggregation);
AggregationResults<ProfileDetails> output = secondaryMongoTemplate.aggregate(aggregation, Profile.class, ProfileDetails.class);
System.out.println("------------------------"+output);
}
}
$out operator replaces documents instead of inserting new documents.How can i make them insert data instead of replacing them

JPA won't save an entity correctly unless the references to other entities are set

If I save this entity using JPA repository with a new defaultAssetId, it will only update the defaultAsssetId to the new value if I set defaultAsset as well. I want to be able to save without setting defaultAsset.
Same problem applies to taskType and assetRole.
package au.com.polonious.conf.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
#Entity
public class TaskTypeAssetRole implements Serializable {
#GenericGenerator(name="tasktypeassetroleidseq",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = {
#Parameter(name = "sequence_name", value = "tasktypeassetroleidseq"),
#Parameter(name = "initial_value", value = "1"),
#Parameter(name = "increment_size", value = "1")
})
#Id
#GeneratedValue(generator = "tasktypeassetroleidseq")
private Long id;
#Column(insertable = false, updatable=false)
private Long taskTypeId;
#Fetch(FetchMode.JOIN)
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="tasktypeid")
private TaskType taskType;
#Column(insertable = false, updatable=false)
private Long assetRoleId;
#Fetch(FetchMode.JOIN)
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="assetRoleId")
private Role assetRole;
#Column(insertable = false, updatable=false)
private Long defaultAssetId;
#Fetch(FetchMode.JOIN)
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="defaultassetid")
private Asset defaultAsset;
private Date startDate;
private Date endDate;
private String notes;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getTaskTypeId() {
return taskTypeId;
}
public void setTaskTypeId(Long taskTypeId) {
this.taskTypeId = taskTypeId;
}
public TaskType getTaskType() {
return taskType;
}
public void setTaskType(TaskType taskType) {
this.taskType = taskType;
}
public Long getAssetRoleId() {
return assetRoleId;
}
public void setAssetRoleId(Long assetRoleId) {
this.assetRoleId = assetRoleId;
}
public Role getAssetRole() {
return assetRole;
}
public void setAssetRole(Role assetRole) {
this.assetRole = assetRole;
}
public Long getDefaultAssetId() {
return defaultAssetId;
}
public void setDefaultAssetId(Long defaultAssetId) {
this.defaultAssetId = defaultAssetId;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
}
I tried saving a taskTypeAssetRole with a new defaultAssedId without setting defaultAsset and I expected the defaultAssedId for that entry in the database to be updated.
What ended up happening was defaultAssetId didn't change although everything else in the entry did update successfully and there were no errors.
Your mapping is inherently broken. The column defaultassetiId is mapped to two different values: the field defaultAssetId and to the id of defaultAsset.
You should remove the defaultAssetId because this construct might break on any update of your JPA provider.
You can use references instead of full entities to set the reference values without loading entities from the database. See https://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/repository/JpaRepository.html#getReferenceById-ID-
If you don't follow this advice you should remove updatable=false if you want to update a field.

Convert Java object to BigQuery TableRow

I am exploring Google Cloud Dataflow.
I was wondering if automatic conversion between java object or JSON to TableRow can be done.
Just like we can automatically parse JSON to POJO class.
I could not find relevant information.
Hope not to duplicate question.
Will be grateful for any info!
Greetings
I've looking for examples for the same with no luck. I created a POJO class that almost match the schema of the bigquery table and matches the structure of the JSON objects that are the input for the pipeline. Finally, when I have to convert those objects to TableRow, for the nested and repeated values I made something like below, and the conversion was made by the API
TableRow row = new TableRow()
.set("items", c.element().getItems())
.set("orderDate", c.element().getOrderDate())
.set("orderNumber", c.element().getOrderNumber());
Where Item class is part of the Order object :
#JsonProperty("items")
private List<Item> items = null;
This is the code for Item class:
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"id",
"code",
"detail",
"name",
"shortName",
"description",
"sku",
"quantity",
"category",
"products"
})
public class Item implements Serializable
{
#JsonProperty("id")
private Integer id;
#JsonProperty("code")
private String code;
#JsonProperty("detail")
private String detail;
#JsonProperty("name")
private String name;
#JsonProperty("shortName")
private String shortName;
#JsonProperty("description")
private String description;
#JsonProperty("sku")
private String sku;
#JsonProperty("quantity")
private Integer quantity;
#JsonProperty("category")
private Category category;
#JsonProperty("products")
private List<Product> products = null;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
private final static long serialVersionUID = -5644586446669059821L;
#JsonProperty("id")
public Integer getId() {
return id;
}
#JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}
#JsonProperty("code")
public String getCode() {
return code;
}
#JsonProperty("code")
public void setCode(String code) {
this.code = code;
}
#JsonProperty("detail")
public String getDetail() {
return detail;
}
#JsonProperty("detail")
public void setDetail(String detail) {
this.detail = detail;
}
#JsonProperty("name")
public String getName() {
return name;
}
#JsonProperty("name")
public void setName(String name) {
this.name = name;
}
#JsonProperty("shortName")
public String getShortName() {
return shortName;
}
#JsonProperty("shortName")
public void setShortName(String shortName) {
this.shortName = shortName;
}
#JsonProperty("description")
public String getDescription() {
return description;
}
#JsonProperty("description")
public void setDescription(String description) {
this.description = description;
}
#JsonProperty("sku")
public String getSku() {
return sku;
}
#JsonProperty("sku")
public void setSku(String sku) {
this.sku = sku;
}
#JsonProperty("quantity")
public Integer getQuantity() {
return quantity;
}
#JsonProperty("quantity")
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
#JsonProperty("category")
public Category getCategory() {
return category;
}
#JsonProperty("category")
public void setCategory(Category category) {
this.category = category;
}
#JsonProperty("products")
public List<Product> getProducts() {
return products;
}
#JsonProperty("products")
public void setProducts(List<Product> products) {
this.products = products;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
And this is the schema of the BigQuery table in regards Items, where Item is a RECORD and REPEATED field and also contain a nested RECORD and REPEATED field: products. See the screenshot of the schema
Item schema fields in BQ

Add data to database adding data to join tables

I'm working in a project and I'm looking to add data to the database, to two join tables.
My parent:
package entity;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the artiste database table.
*
*/
#Entity
#NamedQuery(name="Artiste.findAll", query="SELECT a FROM Artiste a")
public class Artiste implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id_artiste")
private int idArtiste;
#Column(name="a_category")
private String aCategory;
#Column(name="a_name")
private String aName;
private String date;
//bi-directional many-to-one association to Seat
#ManyToOne
#JoinColumn(name="id_seat")
private Seat seat;
public Artiste() {
}
public int getIdArtiste() {
return this.idArtiste;
}
public void setIdArtiste(int idArtiste) {
this.idArtiste = idArtiste;
}
public String getACategory() {
return this.aCategory;
}
public void setACategory(String aCategory) {
this.aCategory = aCategory;
}
public String getAName() {
return this.aName;
}
public void setAName(String aName) {
this.aName = aName;
}
public String getDate() {
return this.date;
}
public void setDate(String date) {
this.date = date;
}
public Seat getSeat() {
return this.seat;
}
public void setSeat(Seat seat) {
this.seat = seat;
}
}
My child:
package entity;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
/**
* The persistent class for the seat database table.
*
*/
#Entity
#NamedQuery(name="Seat.findAll", query="SELECT s FROM Seat s")
public class Seat implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id_seat")
private int idSeat;
private String seat_CA;
private String seat_CB;
private String seat_CC;
private String seat_CD;
//bi-directional many-to-one association to Artiste
#OneToMany(mappedBy="seat")
private List<Artiste> artistes;
public Seat() {
}
public int getIdSeat() {
return this.idSeat;
}
public void setIdSeat(int idSeat) {
this.idSeat = idSeat;
}
public String getSeat_CA() {
return this.seat_CA;
}
public void setSeat_CA(String seat_CA) {
this.seat_CA = seat_CA;
}
public String getSeat_CB() {
return this.seat_CB;
}
public void setSeat_CB(String seat_CB) {
this.seat_CB = seat_CB;
}
public String getSeat_CC() {
return this.seat_CC;
}
public void setSeat_CC(String seat_CC) {
this.seat_CC = seat_CC;
}
public String getSeat_CD() {
return this.seat_CD;
}
public void setSeat_CD(String seat_CD) {
this.seat_CD = seat_CD;
}
public List<Artiste> getArtistes() {
return this.artistes;
}
public void setArtistes(List<Artiste> artistes) {
this.artistes = artistes;
}
public Artiste addArtiste(Artiste artiste) {
getArtistes().add(artiste);
artiste.setSeat(this);
return artiste;
}
public Artiste removeArtiste(Artiste artiste) {
getArtistes().remove(artiste);
artiste.setSeat(null);
return artiste;
}
}
My client:
Artiste a= new Artiste();
Seat b = new Seat();
b.setSeat_CA(request.getParameter("w"));
b.setSeat_CB(request.getParameter("x"));
b.setSeat_CD(request.getParameter("y"));
b.setSeat_CC(request.getParameter("z"));
a.setIdArtiste(b.getIdSeat());
seatFacade.create(b);
a.setAName(request.getParameter("a_name"));
a.setACategory(request.getParameter("a_category"));
a.setDate(request.getParameter("date"));
artisteFacade.create(a);
And I create the FACADE for each one.
Now I can add data but i need also the program add the FOREIGN KEY.
You don't need to get the foreign key, JPA is do every thing, so you should just make it in the right way, so you entities should look like this:
Artiste Entity
#ManyToOne
#JoinColumn(name="id_seat")
private Seat seat;
Seat Entity
#OneToMany(mappedBy="seat", cascade = CascadeType.ALL)
private List<Artiste> artistes = new ArrayList<>();
Your code should look like this:
Artiste a= new Artiste();
Seat b = new Seat();
b.setSeat_CA(request.getParameter("w"));
b.setSeat_CB(request.getParameter("x"));
b.setSeat_CD(request.getParameter("y"));
b.setSeat_CC(request.getParameter("z"));
a.setAName(request.getParameter("a_name"));
a.setACategory(request.getParameter("a_category"));
a.setDate(request.getParameter("date"));
//add this the Article to the list of Seat like this.
b.getArtistes().add(a);
//a.setIdArtiste(b.getIdSeat()); you don't need this
//artisteFacade.create(a); you dont need this also
//set the Seal to your article
a.setSeat(b);
seatFacade.create(b);
So when you persist the Seat the list of articles will persist automaticlly.
This will help you.
You can learn more here : JPA #ManyToOne with CascadeType.ALL

404 Not Found error while consuming REST on EJB

I developed an messaging EJB application with its services that uses WILDFLY 9 server.
Now the application is working and the database is fully functional, I am trying to develop a REST web-service for this app. So I created my RestActivator :
package tn.carmate.webservice;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
#ApplicationPath("rest")
public class RestActivator extends Application {
}
and my messageRessources.java as follows
package tn.carmate.webservice;
import java.util.List;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import tn.esprit.pi.Services.Services;
import tn.esprit.pi.persistance.Message;
#Path("message")
#RequestScoped
public class MessageRessource {
#EJB
Services servicemessage;
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("{idreceiver}")
public Response getMessageList(#QueryParam(value = "idreceiver") int idReceiver) {
List<Message> message = servicemessage.getMessageList(idReceiver);
return Response.status(Status.OK).entity(message).build();
}
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Path("{idSrc/idDest/content}")
public Response sendMessage(#QueryParam(value = "idSrc") int idSrc, #QueryParam(value = "idDest") int idDest,
#QueryParam(value = "content") String content) {
servicemessage.sendMessage(idSrc, idDest, content);
return Response.status(Status.OK).build();
}
#DELETE
#Path("{idm}")
public Response deleteMessage(#QueryParam(value = "idm") int id) {
servicemessage.deleteMessage(id);
return Response.status(Status.OK).build();
}
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("{idSender/idReceiver}")
public Response getConversation(#QueryParam(value = "idSender") int idSender,
#QueryParam(value = "idReceiver") int idReceiver) {
List<Message> conversion = servicemessage.getConversation(idSender, idReceiver);
return Response.status(Status.OK).entity(conversion).build();
}
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("{idR}")
public Response returnInbox (#QueryParam(value = "idR")int idR){
List<Message> listmessage = servicemessage.returnInbox(idR);
return Response.status(Status.OK).entity(listmessage).build();
}
#DELETE
#Path("{idc}")
public Response deleteConversation(#QueryParam(value = "idc")int id){
servicemessage.deleteConversation(id);
return Response.status(Status.OK).build();
}
}
but whenever I try to consume a service like this one I get this error:
This is the message Entity
package tn.esprit.pi.persistance;
import java.io.Serializable;
import java.lang.String;
import java.util.Date;
import javax.persistence.*;
/**
* Entity implementation class for Entity: Message
*
*/
#Entity(name="message")
public class Message implements Serializable {
/* #EmbeddedId
private MessageId Id;
*/
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String object;
private String content;
#Temporal(TemporalType.TIMESTAMP)
private Date dateEmission;
#ManyToOne
private User sender;
#ManyToOne
private User receiver;
private static final long serialVersionUID = 1L;
public Message(User src, User dest, String content) {
this.sender = src;
this.receiver = dest;
this.content = content;
this.dateEmission = new Date();
}
public Message() {
super();
}
/* public MessageId getId() {
return Id;
}public void setId(MessageId id) {
Id = id;
}
*/
public int getIdMessage() {
return this.id;
}
public String getObject() {
return this.object;
}
public void setObject(String object) {
this.object = object;
}
public User getReceiver() {
return this.receiver;
}
public void setReceiver(User reciver) {
this.receiver = reciver;
}
public User getSender() {
return this.sender;
}
public void setSender(User sender) {
this.sender = sender;
}
public String getContent() {
return this.content;
}
public void setContent(String content) {
this.content = content;
}
public Date getDateEmission() {
return this.dateEmission;
}
public void setDateEmission(Date dateEmission) {
this.dateEmission = dateEmission;
}
}
Double check your URL, I think it should be
http://localhost:8080 not http://localhost:18080. Just a typo mistake.
Secondly, Application base path for restful services set to rest
so url should be
http://localhost:8080/CarMate-web/rest/message?idreceiver=1
Finally, idreceiver is a Query Parameter but #Path("{idreceiver}") treat it as path parameter.
So, In http://localhost:8080/CarMate-web/rest/message?idreceiver=1
Rest Endpoint expect a path variable after /message/{idreceiver}?idreceiver=1 as mentioned by #Leonardo in comments.
I would suggest any of below listed solutions:
Remove #Path from method
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response getMessageList(#QueryParam(value = "idreceiver") int idReceiver) {
List<Message> message = servicemessage.getMessageList(idReceiver);
return Response.status(Status.OK).entity(message).build();
}
and use this URL: http://localhost:8080/CarMate-web/rest/message?idreceiver=1
Or Change #Path("{idreceiver}") to #Path("idreceiver")
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("idreceiver")
public Response getMessageList(#QueryParam(value = "idreceiver") int idReceiver) {
List<Message> message = servicemessage.getMessageList(idReceiver);
return Response.status(Status.OK).entity(message).build();
}
and use this URL: http://localhost:8080/CarMate-web/rest/message/idreceiver?idreceiver=1