Neo4j nested relations loading using spring data repository - java

I have the following classes
import java.util.Set;
import org.neo4j.ogm.annotation.GeneratedValue;
import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
#NodeEntity
public class Client {
#Id
#GeneratedValue
private Long id;
private String name;
#Relationship(type = "HAS_CONFIGURED", direction = Relationship.OUTGOING)
public Set<Environment> environments;
public Client () {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Environment> getEnvironments() {
return environments;
}
public void setEnvironments(Set<Environment> environments) {
this.environments = environments;
}
}
import java.util.Set;
import org.neo4j.ogm.annotation.GeneratedValue;
import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
#NodeEntity
public class Environment {
#Id
#GeneratedValue
private Long id;
private String name;
#Relationship(type = "HAS_INSTALLED", direction = Relationship.OUTGOING)
public Set<Application> applications;
public Environment() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Application> getApplications() {
return applications;
}
public void setApplications(Set<Application> applications) {
this.applications = applications;
}
}
import java.util.Set;
import org.neo4j.ogm.annotation.GeneratedValue;
import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
import org.neo4j.ogm.annotation.RelationshipEntity;
#NodeEntity
public class Application {
#Id
#GeneratedValue
private Long id;
private String name;
#Relationship(type = "CAN_THROW", direction = Relationship.OUTGOING)
public Set<Error> errors;
public Application() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Error> getErrors() {
return errors;
}
public void setErrors(Set<Error> errors) {
this.errors = errors;
}
}
And I am trying to load them all using a crud repository
import java.util.List;
import org.springframework.data.neo4j.annotation.Query;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import com.nic.loganalyzer.loganalyzer.model.entity.graph.Client;
public interface ClientRepository extends Neo4jRepository<Client, Long> {
List<Client> findAllByName(String name);
}
Hierarchy is like Client-->Environment-->Application--Error.
The problem is that it loads only till Applications but Application does not load environments.
Is it loaded eagerly?
Or else how can I load the entire structure and traverse.
The way I traverse is as follows
List<Client> findAllByName = clientRepository.findAllByName(eventLog.getClient());
for (Client client: findAllByName) {
List<Environment> environments = client.getEnvironments().stream()
.filter(e -> e.getName().equalsIgnoreCase(eventLog.getEnvironment()))
.collect(Collectors.toList());
for (Environment environment : environments) {
List<Application> applications = environment.getApplications().stream()
.filter(e -> e.getName().equalsIgnoreCase(eventLog.getApplication()))
.collect(Collectors.toList());
for (Application application : applications) {
List<Error> errors = application.getErrors().stream()
.filter(e -> eventLog.getError().contains(e.getName()))
.collect(Collectors.toList());

As far as I understand, the default "depth" value on derived finders is 1.
If you want to load the whole hierarchy, try adding #Depth(value = 3) on top of your derived finder.
Your method should look like:
#Depth(value = 3)
List<Client> findAllByName(String name);

Related

Return key value of a JSON request in Spring

I'm trying to create a route to perform a GET Request to /winner to show the restaurants that had the count of 3 votes in the JSON, but every time I do the GET, it returns the value of null instead of the value I would like.
I was expecting something like that:
{
"id": 1,
"restaurant": "Burger King",
"address": "Av. Ipiranga, 1600",
"website": "https://www.burgerking.com.br/",
"description": "Rede de fast-food famosa com hambúrgueres grelhados, batata frita e milk-shakes.",
"count": 3
}
Instead that, I'm just getting an empty JSON with the null value.
Here are the classes I'm using:
Restaurant.java
package com.dbserver.restaurantes.entities;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "db_restaurants")
public class Restaurant {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String restaurant;
private String address;
private String website;
private String description;
private Integer count;
#OneToMany(mappedBy = "id.restaurant")
private Set<Vote> votes = new HashSet<>();
public Restaurant() {
}
public Restaurant(Long id, String restaurant, String address, String website, String description, Integer count) {
this.id = id;
this.restaurant = restaurant;
this.address = address;
this.website = website;
this.description = description;
this.count = count;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRestaurant() {
return restaurant;
}
public void setRestaurant(String restaurant) {
this.restaurant = restaurant;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public Set<Vote> getVotes() {
return votes;
}
}
RestaurantDTO.java
package com.dbserver.restaurantes.dto;
import com.dbserver.restaurantes.entities.Restaurant;
public class RestaurantDTO {
private Long id;
private String restaurant;
private String address;
private String website;
private String description;
private Integer count;
public RestaurantDTO() {
}
public RestaurantDTO(Long id, String restaurant, String address, String website, String description, Integer count) {
this.id = id;
this.restaurant = restaurant;
this.address = address;
this.website = website;
this.description = description;
this.count = count;
}
public RestaurantDTO(Restaurant restaurantDTO) {
id = restaurantDTO.getId();
restaurant = restaurantDTO.getRestaurant();
address = restaurantDTO.getAddress();
website = restaurantDTO.getWebsite();
description = restaurantDTO.getDescription();
count = restaurantDTO.getCount();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRestaurant() {
return restaurant;
}
public void setRestaurant(String restaurant) {
this.restaurant = restaurant;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
}
RestaurantServices.java
package com.dbserver.restaurantes.services;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dbserver.restaurantes.dto.RestaurantDTO;
import com.dbserver.restaurantes.dto.VoteDTO;
import com.dbserver.restaurantes.entities.Restaurant;
import com.dbserver.restaurantes.repositories.RestaurantRepository;
#Service
public class RestaurantServices {
#Autowired
private RestaurantRepository repository;
#Transactional(readOnly = true)
public Page<RestaurantDTO> findAll(Pageable pageable) {
Page<Restaurant> result = repository.findAll(pageable);
Page<RestaurantDTO> page = result.map(x -> new RestaurantDTO(x));
return page;
}
#Transactional(readOnly = true)
public RestaurantDTO findById(Long id) {
Restaurant result = repository.findById(id).get();
RestaurantDTO dto = new RestaurantDTO(result);
return dto;
}
#Transactional(readOnly = true)
public Restaurant findWinner(Integer count) {
List<Restaurant> restaurants = new ArrayList<>();
for (Restaurant restaurant: restaurants) {
if(restaurant.getCount().equals(3)) {
return restaurant;
}
}
return null;
}
#Transactional
public Restaurant addRestaurant(Restaurant newRestaurant) {
return repository.saveAndFlush(newRestaurant);
}
}
RestaurantController.java
package com.dbserver.restaurantes.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.dbserver.restaurantes.dto.RestaurantDTO;
import com.dbserver.restaurantes.entities.Restaurant;
import com.dbserver.restaurantes.services.RestaurantServices;
#RestController
#RequestMapping(value = "/restaurants")
public class RestaurantController {
#Autowired
private RestaurantServices service;
#GetMapping
public Page<RestaurantDTO> findAll(Pageable pageable) {
return service.findAll(pageable);
}
#GetMapping(value = "/{id}")
public RestaurantDTO findById(#PathVariable Long id) {
return service.findById(id);
}
#SuppressWarnings("unchecked")
#GetMapping(value = "/winner")
public List<RestaurantDTO> findWinner(Integer count) {
return (List<RestaurantDTO>) service.findWinner(3);
};
#PostMapping
public Restaurant addRestaurant(#RequestBody Restaurant newRestaurant) {
return service.addRestaurant(newRestaurant);
}
}
you didn't access dao in the method findWinner.
restaurants instance has just created without accessing dao.
#Transactional(readOnly = true)
public Restaurant findWinner(Integer count) {
List<Restaurant> restaurants = new ArrayList<>();
for (Restaurant restaurant: restaurants) {
if(restaurant.getCount().equals(3)) {
return restaurant;
}
}
return null;
}
because in the find winner method you have initialized restaurants with an empty array list.
It should be like this.
#Transactional(readOnly = true)
public Restaurant findWinner(Integer count) {
List<Restaurant> restaurants = repository.findAll();
for (Restaurant restaurant: restaurants) {
if(restaurant.getCount().equals(3)) {
return restaurant;
}
}
return null;
}

Wrong query generation by hibernate JPA - ManyToMany

here my entities classes linked by ManyToMany:
Product :
package fr.test;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "product")
public class ProductDTO {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name = "product_id")
private int id;
public int getId() {return id;}
public void setId(int id) {this.id = id;}
#Column(name = "nom_product")
private String nom;
public String getNom() {return nom;}
public void setNom(String nom) {this.nom = nom;}
#Column(name = "application")
private String application;
public String getGroupeApplication() {return groupeApplication;}
public void setGroupeApplication(String groupeApplication) {this.groupeApplication = groupeApplication;}
#Column(name = "grp_app")
private String groupeApplication;
public String getApplication() {return application;}
public void setApplication(String application) {this.application = application;}
#ManyToMany
#JoinTable(name = "product_mot_cle")
private List<MotCleDTO> motscleInterdits;
public List<MotCleDTO> getMotscleInterdits() {return motscleInterdits;}
public void setMotscleInterdits(List<MotCleDTO> motscleInterdits) {this.motscleInterdits = motscleInterdits;}
#ManyToMany
#JoinTable(name ="product_extension")
private List<ExtensionDTO> extensionsDisponibles;
public List<ExtensionDTO> getExtensionsDisponibles() {return extensionsDisponibles;}
public void setExtensionsDisponibles(List<ExtensionDTO> extensionsDisponibles) {this.extensionsDisponibles = extensionsDisponibles;}
#OneToMany(mappedBy="prodDiff")
List<DiffusionDTO> destinatairesPrincipaux;
public List<DiffusionDTO> getDestinatairesPrincipaux() {return destinatairesPrincipaux;}
public void setDestinatairesPrincipaux(List<DiffusionDTO> destinatairesPrincipaux) {this.destinatairesPrincipaux = destinatairesPrincipaux;}
#OneToMany(mappedBy="product")
private List<LivraisonDTO> prodLivr;
public List<LivraisonDTO> getProdLivr() {return prodLivr;}
public void setProdLivr(List<LivraisonDTO> prodLivr) {this.prodLivr = prodLivr;}
#ManyToMany(mappedBy="prodList")
private List<EnvironnementDTO> envList;
public List<EnvironnementDTO> getEnvList() {return envList;}
public void setEnvList(List<EnvironnementDTO> envList) {this.envList = envList;}
public ProductDTO() {
}
public ProductDTO(int id, String nom, String appli, String grpAppli) {
this.id = id;
this.nom = nom;
this.application = appli;
this.groupeApplication = grpAppli;
}
}
and Environnment :
#Entity
#Table(name="environnement")
public class EnvironnementDTO {
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE)
#Column(name="environnement_id")
private int id;
public int getId() {return id;}
public void setId(int id) {this.id = id;}
#Column(name="machine_alias")
private String machineAlias;
public String getMachineAlias() {return machineAlias;}
public void setMachineAlias(String machineAlias) {this.machineAlias = machineAlias;}
#Column(name="instance")
private String instance;
public String getInstance() {return instance;}
public void setInstance(String instance) {this.instance = instance;}
#Column(name="port")
private String port;
public String getPort() {return port;}
public void setPort(String port) {this.port = port;}
#OneToMany(mappedBy="environnement")
private List<LivraisonDTO> livrEnv;
public List<LivraisonDTO> getLivrEnv() {return livrEnv;}
public void setLivrEnv(List<LivraisonDTO> livrEnv) {this.livrEnv = livrEnv;}
#ManyToMany
#JoinTable(name="lien_product_environnement",
joinColumns=#JoinColumn(name="environnement_id", referencedColumnName="environnement_id"),
inverseJoinColumns=#JoinColumn(name="product_id",referencedColumnName="product_id"))
private List<ProductDTO> prodList;
public List<ProductDTO> getProdList() {return prodList;}
public void setProdList(List<ProductDTO> prodList) {this.prodList = prodList;}
public EnvironnementDTO() {
}
public EnvironnementDTO(int id, String machineAlias, String instance, String port) {
this.id = id;
this.machineAlias = machineAlias;
this.instance = instance;
this.port = port;
}
}
here my JPQL query :
SELECT env FROM EnvironnementDTO env JOIN ProductDTO p WHERE p.id=2
The generated query on postgres is the following :
select environnem0_.environnement_id as environn1_3_, environnem0_.instance as instance2_3_, environnem0_.machine_alias as machine_3_3_, environnem0_.port as port4_3_ from environnement environnem0_ inner join product productdto1_ on where productdto1_.product_id=2
as you can see : the sql executed on postgres dot not follow the mapping table for many to many designated in #JoinTable on EnvironnementDTO..
We double-checked our annotations, seems jpa or hibernate does not use them to generate the good query !
I'm aware it's certainly a mistake on my side... but don't understand what's happening.
You have to mention the association on which you want to join in the query
SELECT env FROM EnvironnementDTO env JOIN env.prodList p WHERE p.id=2

Getting HTTP Error 500 while mapping JAXB classes

I'm just learning to develop a REST application using JAXB and JPA. I'm stuck in weird problem and I have no clue what to search for.
I have these two classes:
package clinic.model;
import java.io.Serializable;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlList;
import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.persistence.oxm.annotations.XmlInverseReference;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
/**
* The persistent class for the patients database table.
*
*/
#Entity
#Table(name="patients")
#NamedQuery(name="Patient.findAll", query="SELECT p FROM Patient p")
#XmlRootElement
public class Patient implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String address;
private String area;
#Temporal(TemporalType.DATE)
private Date dob;
private BigDecimal mobile;
private String name;
private String sex;
//bi-directional many-to-one association to Prescription
#OneToMany(mappedBy="patient")
private List<Prescription> prescriptions;
public Patient() {
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getArea() {
return this.area;
}
public void setArea(String area) {
this.area = area;
}
public Date getDob() {
return this.dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public BigDecimal getMobile() {
return this.mobile;
}
public void setMobile(BigDecimal mobile) {
this.mobile = mobile;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return this.sex;
}
public void setSex(String sex) {
this.sex = sex;
}
#XmlList
public List<Prescription> getPrescriptions() {
return this.prescriptions;
}
public void setPrescriptions(List<Prescription> prescriptions) {
this.prescriptions = prescriptions;
}
public Prescription addPrescription(Prescription prescription) {
getPrescriptions().add(prescription);
prescription.setPatient(this);
return prescription;
}
public Prescription removePrescription(Prescription prescription) {
getPrescriptions().remove(prescription);
prescription.setPatient(null);
return prescription;
}
}
And
package clinic.model;
import java.io.Serializable;
import javax.persistence.*;
import org.eclipse.persistence.oxm.annotations.XmlInverseReference;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
/**
* The persistent class for the prescriptions database table.
*
*/
#Entity
#Table(name="prescriptions")
#NamedQuery(name="Prescription.findAll", query="SELECT p FROM Prescription p")
public class Prescription implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
#Temporal(TemporalType.DATE)
private Date date;
private BigDecimal fee;
#Temporal(TemporalType.DATE)
private Date followup;
private String treatment;
//bi-directional many-to-one association to Patient
#ManyToOne(fetch=FetchType.LAZY)
private Patient patient;
//bi-directional many-to-many association to Diagnosis
#ManyToMany
#JoinTable(
name="prescriptions_diagnoses"
, joinColumns={
#JoinColumn(name="pid")
}
, inverseJoinColumns={
#JoinColumn(name="did")
}
)
private List<Diagnosis> diagnoses;
//bi-directional many-to-one association to PrescriptionDrug
#OneToMany(mappedBy="prescription")
private List<PrescriptionDrug> prescriptionsDrugs;
//bi-directional many-to-many association to Vaccine
#ManyToMany(mappedBy="prescriptions")
private List<Vaccine> vaccines;
public Prescription() {
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getDate() {
return this.date;
}
public void setDate(Date date) {
this.date = date;
}
public BigDecimal getFee() {
return this.fee;
}
public void setFee(BigDecimal fee) {
this.fee = fee;
}
public Date getFollowup() {
return this.followup;
}
public void setFollowup(Date followup) {
this.followup = followup;
}
public String getTreatment() {
return this.treatment;
}
public void setTreatment(String treatment) {
this.treatment = treatment;
}
public Patient getPatient() {
return this.patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
public List<Diagnosis> getDiagnoses() {
return this.diagnoses;
}
public void setDiagnoses(List<Diagnosis> diagnoses) {
this.diagnoses = diagnoses;
}
public List<PrescriptionDrug> getPrescriptionsDrugs() {
return this.prescriptionsDrugs;
}
public void setPrescriptionsDrugs(List<PrescriptionDrug> prescriptionsDrugs) {
this.prescriptionsDrugs = prescriptionsDrugs;
}
public PrescriptionDrug addPrescriptionsDrug(PrescriptionDrug prescriptionsDrug) {
getPrescriptionsDrugs().add(prescriptionsDrug);
prescriptionsDrug.setPrescription(this);
return prescriptionsDrug;
}
public PrescriptionDrug removePrescriptionsDrug(PrescriptionDrug prescriptionsDrug) {
getPrescriptionsDrugs().remove(prescriptionsDrug);
prescriptionsDrug.setPrescription(null);
return prescriptionsDrug;
}
public List<Vaccine> getVaccines() {
return this.vaccines;
}
public void setVaccines(List<Vaccine> vaccines) {
this.vaccines = vaccines;
}
}
When I have a patient entry in the database, the service is able to map entities into XML/JSON. But when I add an associating prescription entry, Glassfish throws error 500.
What could be the problem?
I'm using GlassFish 4.0 and EclipseLink 2.5.1. IDE is Eclipse Luna.
Solution found at http://blog.bdoughan.com/2010/07/jpa-entities-to-xml-bidirectional.html
The exception can be seen if a string is returned instead of the POJO object and the marshaling is done manually.

ebean model update not permanent

Good day! I'm having a problem when updating an entity. When I click the "update" button, the changes are saved. However, when I go a different page, the recently changed (or added) items are there but the old items (that should be changed or removed) are also there. Particularly the relatedTags (the name and notes are updating just fine). Why is it not persistent or permanent?
Here is where the updating happens.
Form<Tag> filledForm = tagForm.fill(Tag.find.byId(id)).bindFromRequest();
Tag editedTag = RelatedTag.findTag(id);
if(filledForm.hasErrors()) {
return badRequest(editTagForm.render(user, editedTag, filledForm, tags));
}
else {
List<RelatedTag> relatedTagsAlloc = new ArrayList<RelatedTag>();
java.util.Map<String, String[]> map = request().body().asFormUrlEncoded();
String[] relatedTags = map.get("relatedTags.tag.name");
String[] relationship = map.get("relatedTags.relationship");
String[] relatedNotes = map.get("relatedTags.relatedNotes");
if (relatedTags != null) {
for (int i = 0; i < relatedTags.length; i++) {
if (RelatedTag.exists(relatedTags[i].trim().toLowerCase().replaceAll("\\s+", " "))) {
relatedTagsAlloc.add(RelatedTag.findByLabel(
relatedTags[i].trim().toLowerCase().replaceAll("\\s+", " "), relationship[i], relatedNotes[i].trim()));
} else {
Tag unknown = new Tag(relatedTags[i], "");
Tag.create(unknown);
relatedTagsAlloc.add(RelatedTag.findByLabel(
relatedTags[i].trim().toLowerCase().replaceAll("\\s+", " "), relationship[i], relatedNotes[i].trim()));
}
}
editedTag.getRelatedTags().clear();
}
editedTag.setName(filledForm.get().getName().toLowerCase().replaceAll("\\s+", " "));
editedTag.setRelatedTags(relatedTagsAlloc);
editedTag.update();
Application.log(user, editedTag, action);
writeToFile(editedTag);
return ok(summary.render(user, editedTag));
}
And here are the models:
Tag model:
package models;
import java.sql.Timestamp;
import java.util.*;
import javax.persistence.*;
import javax.validation.*;
import play.data.Form;
import play.data.validation.Constraints.*;
import play.db.ebean.*;
import play.db.ebean.Model.Finder;
import scala.Int;
#Entity
public class Tag extends Model{
#Id
private int id;
#Required
#MaxLength(value=100)
#Column(unique=true)
private String name;
#MaxLength(value=200)
private String notes;
#OneToMany(cascade=CascadeType.ALL)
public List<RelatedTag> relatedTags = new ArrayList<RelatedTag>();
#Version
public Timestamp lastUpdate;
public static Finder<Integer, Tag> find = new Finder(Int.class, Tag.class);
public Tag() {
}
public Tag(String name, String notes){
this.name = name;
this.notes = notes;
}
public Tag(int id, String name, String notes, List<RelatedTag> relatedTags) {
this.id = id;
this.name = name;
this.notes = notes;
this.relatedTags = relatedTags;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public List<RelatedTag> getRelatedTags() {
return relatedTags;
}
public void setRelatedTags(List<RelatedTag> relatedTags) {
this.relatedTags = relatedTags;
}
public static List<Tag> all() {
return find.all();
}
public static void create(Tag tag){
tag.save();
}
public static void delete(int id){
find.ref(id).delete();
}
public static void update(int id, Tag tag) {
tag.update(id); // updates this entity, by specifying the entity ID
}
public static boolean exists(Tag newTag) {
for(Tag allTags : Tag.find.all()) {
if(allTags.getName().equals(newTag.getName()))
return true;
}
return false;
}
}
RelatedTag model
package models;
import java.sql.Timestamp;
import java.util.*;
import javax.persistence.*;
import javax.validation.*;
import play.data.Form;
import play.data.validation.Constraints.*;
import play.db.ebean.*;
import play.db.ebean.Model.Finder;
import scala.Int;
#Entity
public class RelatedTag extends Model {
#Id
public int rtID;
private int id; //same as Tag's id
private String relationship;
private String relatedNotes;
#Version
public Timestamp lastUpdate;
public RelatedTag() {}
public RelatedTag(int id, String relationship, String relatedNotes) {
this.id = id;
this.relationship = relationship;
this.relatedNotes = relatedNotes;
}
public void setId(int id){
this.id = id;
}
public void setRelationship(String relationship){
this.relationship = relationship;
}
public void setRelatedNotes(String relatedNotes) {
this.relatedNotes = relatedNotes;
}
public int getId(){
return id;
}
public String getRelationship(){
return relationship;
}
public String getRelatedNotes() {
return relatedNotes;
}
public static void create(List<RelatedTag> rt){
((Model) rt).save();
}
public static boolean exists(String tagRelated) {
for(Tag tag : Tag.find.all()) {
if(tagRelated.equals(tag.getName()))
return true;
}
return false;
}
public static RelatedTag findByLabel(String tagRelated, String relation, String relatedNotes) {
RelatedTag relatedTag = null;
for(Tag tag : Tag.find.all()) {
if(tagRelated.equals(tag.getName())) {
relatedTag = new RelatedTag(tag.getId(), relation, relatedNotes);
}
}
return relatedTag;
}
public static Tag findTag(int id) {
for(Tag tag : Tag.find.all()) {
if(id == tag.getId())
return tag;
}
return null;
}
}
What have I been doing wrong? Please help me fix this. Thank you very much!

spring-data-neo4j findByPropertyValue method always return null?

i've got Social model :
import java.util.Set;
import org.neo4j.graphdb.Direction;
import org.springframework.data.neo4j.annotation.Fetch;
import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.Indexed;
import org.springframework.data.neo4j.annotation.NodeEntity;
import org.springframework.data.neo4j.annotation.RelatedTo;
#NodeEntity
public class Social {
#GraphId
private Long id;
#Indexed
private Long userId;
#RelatedTo(type="FRIEND", direction=Direction.BOTH)
#Fetch private Set<Social> friends;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Set<Social> getFriends() {
return friends;
}
public void setFriends(Set<Social> friends) {
this.friends = friends;
}
public void addFriend(Social social){
this.friends.add(social);
}
}
and repository :
import org.springframework.data.neo4j.repository.GraphRepository;
import org.springframework.data.neo4j.repository.RelationshipOperationsRepository;
import com.msci.travelpad.entities.Social;
public interface SocialRepository extends GraphRepository<Social>, RelationshipOperationsRepository<Social> {
}
but when i would to find social node by userId using :
public Social findByUserId(Long userId) {
return socialRepository.findByPropertyValue("userId", userId);
}
findByUserId always return null.
Did you try to implement your own find method in the repository like:
Iterable<Social> findByUserId(Long userId);
Are the indexes created correctly (see Null return using GraphRepository from Spring Data for Neo4j)?

Categories

Resources