I am writing some test code to learn spring-data with MongoDB. I can successfully create two Documents: Person and ADocument, where ADocument contains a reference to Person.
#Document
public class Person {
#Id
private ObjectId id;
#Indexed
private String name;
public ObjectId getId() {
return id;
}
public void setId(ObjectId id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
...
#Document
public class ADocument {
#Id
private ObjectId id;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
private String title;
private String text;
#DBRef
private Person docperson;
public Person getDocperson() {
return docperson;
}
public void setDocperson(Person docperson) {
this.docperson = docperson;
}
public ObjectId getId() {
return id;
}
public void setId(ObjectId id) {
this.id = id;
}
}
The problem arises when I try to get all the 'adocuments' related to a person by using the person's ID (once the person's name is provided):
public List<ADocument> loadDocumentsByPersonName(String pname) {
Query qPerson = new Query().addCriteria(Criteria.where("name").is(pname));
qPerson.fields().include("_id");
Person pers = mongoTemplate.findOne(qPerson, Person.class);
ObjectId persId = pers.getId();
Query qDoc = new Query().addCriteria(Criteria.where("person.$id").is(persId));
System.out.println(qDoc.toString());
List<ADocument> list2 = mongoTemplate.find(qDoc, ADocument.class);
return list2;
}
Everyting works fine except that list2 is always empty (while it shouldn't).
System.out.println(qDoc.toString()) gives something like:
Query: { "person.$id" : { "$oid" : "536a0d50e4b0d0c10297f2ab"}}, Fields: null, Sort: null
If I try to issue the query above on the Mongo shell I get the following:
db.adocument.find({ "person.$id" : { "$oid" : "536a0805e4b0af174d0b5871"}})
error: {
"$err" : "Can't canonicalize query: BadValue unknown operator: $oid",
"code" : 17287
}
While if I type
db.adocument.find({ "person.$id" : ObjectId("536a0805e4b0af174d0b5871")})
I actually get a result!
I am using MongoDB 2.6.0 and Spring Data 1.4.2.
I really can't figure out what's going on... Any help is extremely appreciated!
I got it!
For some reason, I had to explicit the collection name in the Query:
List list2 = mongoTemplate.find(qDoc, ADocument.class, COLLECTION_NAME);
where COLLECTION_NAME="adocument".
As for the shell behaviour, it seems that Query.toString() does never return a correct syntax to be cut and paste for shell execution.
Related
I am currently building a rest api that lets the user enter a recipe and describe it. I am using spring-boot as backend and angularjs as frontend.
This is springboot recipe file
package com.example.springboot;
import com.example.springboot.Recipe;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
#Entity // This tells Hibernate to make a table out of this class
public class Recipe {
public Recipe(){
}
public Recipe(Integer id, String name, String description, String type, Integer preptime, Integer cooktime, String content, Integer difficulty){
this.id = id;
this.name = name;
this.description = description;
this.type = type;
this.preptime = preptimee;
this.cooktime = cooktime;
this.content = content;
this.difficulty = difficulty;
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
private String description;
private String type;
private Integer preptime;
#Column(columnDefinition = "TEXT")
private String content;
private Integer difficulty;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Integer getDifficulty() {
return difficulty;
}
public void setDifficulty(Integer difficulty) {
this.difficulty = difficulty;
}
public Integer getpreptime {
return preptime;
}
public void setpreptime(Integer preptime) {
this.preptime = preptime;
}
}
I created an Endpoint where the user can edit the whole recipe. The user can edit the name , description, content and so on in the recipes/edit/{id} endpoint.
The Endpoint looks like this.
#PutMapping("/recipes/edit/{id}")
void updateRecipe(#PathVariable int id, #RequestBody Recipe recipe ) {
System.out.println("entering");
Recipe recipe_ = recipeRepository.findById(id).get();
recipe_.setName(recipe.getName());
recipe_.setDescription(recipe.getDescription());
recipe_.setType(recipe.getType());
recipe_.setpreptime(recipe.getpreptime());
recipe_.setContent(recipe.getContent());
System.out.println("entering " + recipe.getTitle());
System.out.println("entering" + recipe.getType());
System.out.println("entering" + recipe.getDescription());
System.out.println("adding");
recipeRepository.save(recipe_);
}
Now I just want to create an Endpoint which only serves the purpose for renaming the name of the recipe. This putmapping should accept a list as its input then only rename the name of the recipe.
#PutMapping("/recipes/rename")
public List<Recipe> {
System.out.println("entering renaming");
// recipe_.setName(recipe.getName()); ?
}
I don't know how I can implement this. This is what I have come up with so far. An endpoint which takes a list as a parameter.
This is the service.ts file that updates the Recipes in the edit function
service.ts:
updateRecipe (id: number, recipe: any): Observable<any > {
const url = `${this.usersUrl}/edit/${id}`;
return this.http.put(url ,recipe);
}
where the updateRecipe gets called:
save(): void {
const id = +this.route.snapshot.paramMap.get('name');
this.recipeService.updateRecipe2(id, this.recipes)
.subscribe(() => this.gotoUserList());
}
This implementation work , I don't know how I can get it work or how I can rewrite the functions so that it can update only the name of the recipe and not the whole file.
Could someone help me?
Your update the name method should look like that:
#PutMapping("...{id}")
public void updateName(#PathVariable Integer id, #RequestParam String name){
Recipe recipe = repository.findById(id).orElseThrow(...);
recipe.setName(name);
}
if you want to rename list of recipes
public void renameRecipes(String oldName, String newName){
repository.findByName(oldName)
.forEach(r -> r.setName(newName));
}
#PutMapping("recipes/rename")
public void updateNames(#PequestParam String oldName, #RequestParam String newName){
renameRecipes(oldName, newName);
}
Try that.
I know there are a few questions on stackoverflow regarding this problem. But I have have been spending hours trying to resolve this error without any success.
I am using the mysql database to store the values.
I keep on getting the error message from the
com.example.springboot.Recipe file.
This is springboot recipe file
package com.example.springboot;
import com.example.springboot.Recipe;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
#Entity // This tells Hibernate to make a table out of this class
public class Recipe {
public Recipe(){
}
public Recipe(Integer id, String name, String description, String type, Integer preptime, Integer cooktime, String content, Integer difficulty){
this.id = id;
this.name = name;
this.description = description;
this.type = type;
this.preptime = preptimee;
this.cooktime = cooktime;
this.content = content;
this.difficulty = difficulty;
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
private String description;
private String type;
private Integer preptime;
private Integer cooktime;
#Column(columnDefinition = "TEXT")
private String content;
private Integer difficulty;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return name;
}
public void setTitle(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Integer getDifficulty() {
return difficulty;
}
public void setDifficulty(Integer difficulty) {
this.difficulty = difficulty;
}
public Integer getCookingtime() {
return cooktime;
}
public void setCookingtimeime(Integer cooktime) {
this.cooktime = cooktime;
}
public Integer getPreparationtime() {
return preptime;
}
public void setPreparationtime(Integer preptime) {
this.preptime = preptime;
}
}
Main Controller:
#PutMapping("/recipes/edit/{id}")
void updateRecipe2(#PathVariable int id, #RequestBody Recipe recipe ) {
Recipe recipe_ = recipeRepository.findById(id).get();
recipe_.setTitle(recipe.getTitle());
System.out.println("sss " + recipe.getname());
System.out.println("change");
recipeRepository.save(recipe_);
}
service.ts:
updateRecipe2 (id: number, recipe: any): Observable<any > {
const url = `${this.usersUrl}/edit/${id}`;
return this.http.put(url ,recipe);
}
where the updateRecipe2 gets called:
save(): void {
const id = +this.route.snapshot.paramMap.get('name');
this.recipeService.updateRecipe2(id, this.recipes)
.subscribe(() => this.gotoUserList());
}
as soon as the user clicks save this functions saves the changes made.
I hope the code snippets that I provided are enough to help solve the problem.
Thank you in advance.
I am building a rest api with spring boot and I am using angularjs as it's frontend. I am pretty new to web-development.
You are sending a list of recipes to an api endpoint that expects a single recipe object.
Your options are:
Send only one recipe object at a time, for example:
this.recipeService.updateRecipe2(id, this.recipes[0])
OR: create a new API endpoint to accept a list of recipes, to edit them in "batch"
#PutMapping("/recipes/edit")
void updateRecipes(#RequestBody List<Recipe> recipe ) {
my Example:
Use:
#PostMapping
Code:
public void setTransacciones(List<Transacciones> transacciones) {
this.transacciones = transacciones;
}
CodeBean:
public class Transacciones {
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
private String text;
}
Post(raw):
{
"transacciones" : [ {"text" : "1"}, {"text" : "2"} ]
}
Result:
{
"transacciones": [
{
"transaccionId": 2,
"text": "1"
},
{
"transaccionId": 3,
"text": "2"
}
]
}
BINGO!!
Here's MVCE: https://github.com/neo4j-examples/movies-java-spring-data-neo4j
If you change one test to:
#Test
public void testFindByTitle() {
String title = "The Matrix";
Movie result = movieRepository.findByTitle(title);
Person p = personRepository.findByName("Keanu Reeves");
assertNotNull(result);
assertEquals(1999, result.getReleased());
}
You can see in debug mode that object p does not have any movies.
Person entity is:
#NodeEntity
public class Person {
#Id
#GeneratedValue
private Long id;
private String name;
private int born;
#Relationship(type = "ACTED_IN")
private List<Movie> movies = new ArrayList<>();
public Person() {
}
public Person(String name, int born) {
this.name = name;
this.born = born;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public int getBorn() {
return born;
}
public List<Movie> getMovies() {
return movies;
}
}
This is offical example from neo4j. How can i store entity Person with movies in database and also have Movie entity with roles ?
Edit: What i can do is add in Person entity method:
public void addMovie(Movie movie) {
if (this.movies == null) {
this.movies = new ArrayList<>();
}
this.movies.add(movie);
}
And in the test add:
p.addMovie(matrix);
personRepository.save(p);
But i don't like this - cause i setting it manually from two sites.
You do not need to set the references manually from two sides. Expand your code snippet slightly by a single line movie.setPerson(this); and you are done:
public void addMovie(#NotNull Movie movie) {
if (this.movies == null)
this.movies = new ArrayList<>();
this.movies.add(movie);
movie.setPerson(this);
}
While there is plenty of information around on how to model, in JPA (2), a one-to-one relationship OR an entity having a natural key, I haven't been able to find a clear / simple answer to how to model the situation where we have both, i.e. a one-to-one relationship where the parent table has a natural key. It could obviously be that I might have missed such a tutorial; if so, pointing me to one could also be the answer.
And, as many times with JPA and noobs such as I, the moment one needs a bit more than the most basic model, one can quickly hit the wall.
Hence, considering the following DB model:
What would be the corresponding JPA-annotated object model? (I'm sparing you guys of the things I've tried since I don't want to influence the answer...)
Performance recommendations are also welcome (e.g. "a one-to-many could perform faster", etc.)!
Thanks,
The composite identifier is built out of two numerical columns so the mapping looks like this:
#Embeddable
public class EmployeeId implements Serializable {
private Long companyId;
private Long employeeId;
public EmployeeId() {
}
public EmployeeId(Long companyId, Long employeeId) {
this.companyId = companyId;
this.employeeId = employeeId;
}
public Long getCompanyId() {
return companyId;
}
public Long getEmployeeId() {
return employeeId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof EmployeeId)) return false;
EmployeeId that = (EmployeeId) o;
return Objects.equals(getCompanyId(), that.getCompanyId()) &&
Objects.equals(getEmployeeId(), that.getEmployeeId());
}
#Override
public int hashCode() {
return Objects.hash(getCompanyId(), getEmployeeId());
}
}
The parent class, looks as follows:
#Entity(name = "Employee")
public static class Employee {
#EmbeddedId
private EmployeeId id;
private String name;
#OneToOne(mappedBy = "employee")
private EmployeeDetails details;
public EmployeeId getId() {
return id;
}
public void setId(EmployeeId id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public EmployeeDetails getDetails() {
return details;
}
public void setDetails(EmployeeDetails details) {
this.details = details;
}
}
And the child like this:
#Entity(name = "EmployeeDetails")
public static class EmployeeDetails {
#EmbeddedId
private EmployeeId id;
#MapsId
#OneToOne
private Employee employee;
private String details;
public EmployeeId getId() {
return id;
}
public void setId(EmployeeId id) {
this.id = id;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
this.id = employee.getId();
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
}
And everything works just fine:
doInJPA(entityManager -> {
Employee employee = new Employee();
employee.setId(new EmployeeId(1L, 100L));
employee.setName("Vlad Mihalcea");
entityManager.persist(employee);
});
doInJPA(entityManager -> {
Employee employee = entityManager.find(Employee.class, new EmployeeId(1L, 100L));
EmployeeDetails employeeDetails = new EmployeeDetails();
employeeDetails.setEmployee(employee);
employeeDetails.setDetails("High-Performance Java Persistence");
entityManager.persist(employeeDetails);
});
doInJPA(entityManager -> {
EmployeeDetails employeeDetails = entityManager.find(EmployeeDetails.class, new EmployeeId(1L, 100L));
assertNotNull(employeeDetails);
});
doInJPA(entityManager -> {
Phone phone = entityManager.find(Phone.class, "012-345-6789");
assertNotNull(phone);
assertEquals(new EmployeeId(1L, 100L), phone.getEmployee().getId());
});
Code available on GitHub.
I am trying to create relationships between nodes in Neo4j. I am using the Neo4J(2.1.8 Community) & spring-data-neo4j(3.3.0.RELEASE).
I am trying to create the below relation.
Create a new Employee(node) which will be reporting(Empty Relation) to the Manager(node) which is there in DB (Searching by name). I have used the below query.
public interface EmployeeRepository extends GraphRepository<Employee> {
#Query("START employee=node:({0}), manager=node:Employee(name={1}) CREATE employee-[:REPORTS_TO]->manager")
void addNewEmployee(Employee employee, String managerName);}
I got the below error.
Caused by: org.springframework.dao.InvalidDataAccessResourceUsageException: Error executing statement START employee=node:({0}), manager=node:Employee(name={1}) CREATE employee-[:REPORTS_TO]->manager; nested exception is Invalid input '(': expected whitespace or an identifier (line 1, column 21)
"START employee=node:({0}), manager=node:Employee(name={1}) CREATE employee-[:REPORTS_TO]->manager"
^
Can anyone please tell me what is wrong with this query? Also if this is not the right way to create the relations using GraphRepository then what else I can use to accomplish the same.
Thanks in advance.
Note: I have used this to learn the queries in Spring Data for Neo4j. Where they have shown the basic queries.
Updated: Employee Class
#NodeEntity
public class Employee {
#GraphId
private Long id;
private String name;
private String department;
#RelatedTo(type = "REPORTS_TO")
private Employee reportsTo;
#RelatedTo(type = "REPORTS_TO", direction = Direction.INCOMING)
Set<Employee> directReport;
public Employee() {
}
public Employee(String name, String department) {
this.name = name;
this.department = department;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public Employee getReportsTo() {
return reportsTo;
}
public void setReportsTo(Employee reportsTo) {
this.reportsTo = reportsTo;
}
public Set<Employee> getDirectReport() {
return directReport;
}
public void setDirectReport(Set<Employee> directReport) {
this.directReport = directReport;
}
#Override
public int hashCode() {
return super.hashCode();
}
#Override
public boolean equals(Object obj) {
return super.equals(obj);
}
#Override
public String toString() {
return "Employee{" + "id=" + id + ", name=" + name + ", department=" + department + '}';
}
}
Please show the definition of employee!
You can also use template.createRelationshipBetween(nodeOrEntity,nodeOrEntity2,type)
For your example this should work:
public interface EmployeeRepository extends GraphRepository {
#Query("MATCH (employee:Employee), (manager:Employee)
WHERE id(employee) = {0} AND manager.name = {1}
CREATE employee-[:REPORTS_TO]->manager")
void addNewEmployee(Employee employee, String managerName);
}
perhaps better use, employee as a data-container / map for employee or just pass in the name directly:
#Query("MATCH (employee:Employee), (manager:Employee)
WHERE employee.name = {0}.name AND manager.name = {1}
CREATE employee-[:REPORTS_TO]->manager")
void addNewEmployee(Employee employee, String managerName);
}