Unable to parse Json to Object : JPA ManytoOne unidirectional - spring

I am using spring data rest with repositories, db is mysql.
I have objects Parent and child. Relationship is Many to one .
child to Parent relationship is unidirectional. I do not have List of child obj inside Parent.
Parent{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id = null;
#NotNull(message = "name of user should not be null")
#Size(min=2, max=30)
private String name;
}
Child{
private String name;
#ManyToOne
private Parent parent;
}
I have an parent "1" and i want to refer it to newly creating child. The json input for new child "POST" req is
{
"name":"child name",
"parent":{
"id":1
}
}
Need help in associating parent "1" in newly creating child.
Is there any changes required in json format? I tried with "parent_id" as well but still having error.

Since spring-data-rest uses HATEOAS. The following format worked.
{
"name":"testname1",
"parent": "http://localhost:8080/parent/2"
}
Thanks to all who tried to answer.

Related

Spring data jpa insert child into parent using rest call

Let's assume we have two entities A and B which have such a relation:
public class A {
#Id
private Integer id;
#OneToMany(mappedBy = "parent")
private Set<B> childs = new HashSet<>();
// getters and setters
}
public class B {
#Id
private Integer id;
#ManyToOne
private A parent;
// getters and setters
}
I'm having 2 repositories, one for each entity (ARepository and BRepository) and i'm using spring data rest starter so i've got generated rest api.
Let assume we have an instance of A, which has as id=12
In order to insert a B entity and link it to A i have to: POST the url http://localhost:8080/appContext/b/ and giving it a request body as follow: {"parent": "a/12"}
It works fine, but it is possible to have the same thing by posting http://localhost:8080/appContext/a/12/childs/ with the same request param except the "parent" JSON attribute ? as it's actually possible to fetch the childs of a parent using this last url.

How to do not send #IdClass object in Spring JSON queries

I'm setting a server to get a CRUD api from a postgresql Database using JPA. Everytime I want to expose an object from the DB it duplicate the idObject.
When I get an object from the database using springframework and send it after that, it duplicate the idObject like this:
{
"siteId": 3,
"contractId": "1",
"name": "sitenumber1",
"siteIdObject": {
"siteId": 3,
"contractId": "1"
}
}
SiteId and contractId are repeating...
but I want something like that:
{
"siteId": 3,
"contractId": "1",
"name": "sitenumber1"
}
I want to avoid using DTO because I think there is a better way but I don't find it. Since I'm using springFramework for just one or two month I'm maybe forgeting something...
there is the code:
Site code:
#Entity
#IdClass(SiteId.class)
#Table(name = "site", schema="public")
public class Site {
#Id
#Column(name="siteid")
private Integer siteId;
#Id
#Column(name="clientid")
private Integer contractId;
private String name;
#JsonIgnore
#OneToMany(cascade=CascadeType.ALL, mappedBy = "site")
public Set<Device> devices;
//setter, getter, hash, equals, tostring, constructor empty one and full one
SiteId code:
public class SiteId implements Serializable {
private Integer siteId;
private Integer contractId;
// setter, getter, constructor empty and full, hash and equals
Thanks to help :)
Bessaix Daniel
If you are using Spring you might also be using Jackson so if you annotate your SiteIdclass with #JsonIgnoreType it shouldn't be serialized at all when the Site object is serialized.
I am however unsure if this will break your application logic now that the id object is not serialized anymore.

Inject data in json entity with Spring Data REST

I have JPA entity for department:
public class Department {
#Id
#Column(unique = true, nullable = false)
private long id;
#Basic
#Column
#Nationalized
private String name;
#Basic
#Column(length = 400)
#Nationalized
private String branch;
...
}
And REST repository
#RepositoryRestResource(collectionResourceRel = "departments", path = "departments")
public interface DepartmentRestRepository extends PagingAndSortingRepository<Department, Long> {
...
}
Entity's branch field is IDs of entity parent departments separated by space, e.g. 1 2 3.
When I query specific department via /api/departments/ID is it possible to attach to it field like parents with all parent entities queried?
I tryed to add getParents method to entity, but it obviously gave me unneeded parents queries with all entities recursively.
Update 2019.01.17:
As a workaround I splitted Department entity into Department and DepartmentWithParents. I added Department getParents() method to DepartmentWithParents entity and exposed REST API method that returns DepartmentWithParents.
Is there better way?
As a workaround I splitted Department entity into Department and DepartmentWithParents. I added Department getParents() method to DepartmentWithParents entity and exposed REST API method that returns DepartmentWithParents.

Bulk data to find exists or not : Spring Data JPA

I get an Post request that would give me a List<PersonApi> Objects
class PersonApi {
private String name;
private String age;
private String pincode ;
}
And I have an Entity Object named Person
#Entity
#Table(name = "person_master")
public class Person{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
#Column(name = "name")
String name;
#Column(name = "age")
String age;
#Column(name = "pincode ")
String pincode ;
}
My record from Post request would look something like this (pseudocode representation of the data below)
[
"Arun","33","09876gh"
"James","34","8765468"
]
I need to do a bulk-validation using Spring JPA.. Give the List<PersonApi> and get a True or False based on the condition that all the entries in the PersonApi objects list should be there in the database.
How to do this ?
The selected answer is not a right one. (not always right)
You are selecting the whole database to check for existence. Unless your use case is very special, i.e. table is very small, this will kill the performance.
The proper way may start from issuing repository.existsById(id) for each Person, if you never delete the persons, you can even apply some caching on top of it.
exists
Pseudo Code:
List<PersonApi> personsApiList = ...; //from request
List<Person> result = personRepository.findAll();
in your service class you can access your repository to fetch all database entities and check if your list of personapi's is completeley available.
boolean allEntriesExist = result.stream().allMatch(person -> personsApiList.contains(createPersonApiFromPerson(person)));
public PersonApi createPersonApiFromPerson(Person person){
return new PersonApi(person.getName(), person.getAge(), person.getPincode());
}

Spring data JPA avoid multiple select in many to one relationship

I'm using Spring Data JPA and have a many to one relationship from Child to Parent Class using hibernate. I'm writing a search API which would search on child table using some child table columns and return list of child objects along with some data from Parent class for each child object. I'm doing by default eager fetch for many to one relationship. The problem i'm facing is lets say after searching child table 10 entries are returned then hibernate is doing 10 different select queries on parent class to get Parent object for each child object. Is there a way to optimize this ? There is a solution given to similar problem here but it is for one to many case. I could not find anything helpful regarding this on web also. Any ideas ?
as you didn't show any codes in the question, it's a little hard to solve it but I think if you specify join column (#JoinColumn annotation) and use #OneToMany annotation in parent class(with specifying fetch type) and #ManyToOne inside child you should not have any problem:
#Entity(name ="Parent")
public class Parent {
#Id
#Column
private int id;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name= "paren_id")
private Set<Child> children;
//getters and setters
}
#Entity(name ="Child")
public class Child{
#Id
#Column
private int id;
#ManyToOne
private Parent parent;
//getters and setters
}

Resources