spring data rest - Create a relationship oneToOne and create the ressource - java

I'm testing spring data rest and I would like make a post on a relation entity.
For exemple :
I've two classes :
one two
----- -----
field field
#OneToOne
fieldTwo
how can I instantiate two ?
when I do post on /one
{
"field":"field",
"field2": {
"field":"field"
}
it doesn't create a field2
when I do post on /one/{idOne}/twos:
"field2": {
"field":"field"
}
it does nothing.
Does somebody have more informations ?
I didn't find any informations about this.
Thanks
Gegko

If I understood correctly you're trying to create records/entities with association using Spring Data Rest.
In Spring Data Rest when you POST for an entity, it won't create automatically the associated entity. instead, you will have to create each entity separately by yourself using rest.
If you want to create entities with association using REST, all you have to do is first create the not owning entity (the entity which doesn't hold the foreign key). when you do that you'll have its rest URL.
the second step is to take that URL and to put it as a foreign key when you try to save the second entity.
Here's an example:
POSTing a #OneToMany sub-resource association in Spring Data REST

Related

Store java object which contains another object on a single table with JPA

I'm doing an exercise with Springboot that basically consists of a simple application with a Rest Controller who has to store an object received from POST request to a mysql db using JPA/Hibernate.
My problem is the following one:
the table has this structure:
And I have this pojo which has to map the table as an object:
If you pay attention, the table has a column named "CARD_HOLDER_FULL_NAME", but in the app, the card holder must be a separate object:
so, how do I specify that the fullName attribuite in the CaldHolderInfo class represents that column in the table?
I'm very rusty with Springboot/JPA/hibernate so I don't know how to proceed
You need to make CaldHolderInfo an Embeddable.
See JPA #Embedded And #Embeddable
And please, no images of code on this site.

SpringBoot: Better way to create multiple entities from a single JSON with all data

I am working on a REST API with the following structure:
controller: classes that define the endpoints to obtain/create entities.
model: classes that represent the entities that are stored in each database table.
repository: classes that extend JpaRepository, it provides the methods to perform HQL queries on each model.
service / serviceimpl: classes that define the logic to obtain or create an entity from a model.
There is a table in the database that has multiple #OneToMany relationships with other tables. From the front-end, I will receive a json with the data to create a new entity from this table, but this json will also contain information to create entities from other tables that are related to the main one. This gives me the following problems:
The model class for the main entity has a lot of #Transient attributes because they send me information that shouldn't be mapped directly to a DB table, because I'll have to implement the logic to create the actual instances. (where should I do it? currently the logic to get child instances is implemented in the parent's ServiceImpl class, so the code is very long and hard to maintain).
I must persist each instance separately: to create the child entities I must provide an id of the parent entity. Because of this, I need to use JpaRepository's .save() method a first time to insert the parent entity and get its id. Then from that id I do the logic to create all the child entities and persist each one. In case there is a problem in the middle of the method, some instances will have been persisted and others not, this implies saving incomplete data in the DB.
The result of this is a very dirty and difficult to maintain model and ServiceImpl class. But I have to do that, since the front-end devs want to send me a single json with the information of everything that needs to be created, and they decided that the back-end implements all the logic to create the entities.
In what classes and in what order would you define the methods to do this as cleanly and safely as possible?
If you use #Transactions and have auto-commit: false, it will commit the changes at the end of the transaction.
So if you created the main object, then create all other subsequent objects and if any of them fails, the transaction will rollback.
Regarding the order of creation:
i would make a creation manager that will handle these. So for example
the json that you receive from the FE is
Apply what says in this answer in the below method.
{
"name": "abc",
"children-ofTypeA": [{
"name": "abc-child-a"
},
"children-ofTypeB": [{
"name": "abc-child-b"
}],
"some-other-prop-that-we-don't-care": {..}
}
class MainObject {
private String name:
private List<A> childrenA;
private List<B> childrenB;
}
You get this json and you pass it to CreationManager for example
class CreationManager {
#Transactional
public void create(StructureAbove json) {
// use a mapper of something to create the object
var mainObj = createMainObjFrom(json);
//apply what says in the posted link
}
}

why in the json i get from jhipster dtos automatic generation give me null one to many relationship?

I generated DTOs with JHipster automatically. I didn't know how to see my json just with console and i get null in one to many relationship.
This is what i get.[OperationDTO{id=1, date='2015-08-05T08:48:00Z', description='Mississippi Account Associate', amount=13968.00, bankAccount=BankAccountDTO{id=1, name='monitor', balance=null, user=null}, labels=[]}]
And i am using this repository from github
https://github.com/jhipster/jhipster-sample-app-dto
Thanks.
This is the intended behaviour: https://www.jhipster.tech/using-dtos/#how-dtos-work-in-jhipster
It will aggregate many-to-one relationships, only using the ID and the field used to display it in your client-side framework
I had the same questions at first. The autogenerated DTOs only provide linking information. Fields which are not the id or display element are left as null.
If this is not what you want, you can modify the MapStruct mappers or define your own conversion to and from DTOs.
You can inspect the JSON via the Swagger interface: Login as admin then go to Admin > API (http://localhost:8080/admin/docs).

Fetching parent data using Child Data in OneToMany JPA Relationship in spring

I have a classic problem where i need to find the parent data by using child data in One To Many JPA relationship
Scenario
I need to find all the student who lives in one city(ex- Delhi) and locality ( ex- west delhi)
I have one class as Studen and Another class as Address , In address class we are having these attributes in Class
I also have StudentRepository , now what Query Method should i write in Repository where i can get all the Students on address Filters basis
I am using Spring boot and Spring data
Please help me
If you need i can share the code!!!
You can use the below method in StudentRepository for the desired result
findByAddressCityAndAddressLocality(String city, String locality);

Initialize ManyToMany on web environment with RESTfull API

As says on To initialize or not initialize JPA relationship mappings? is good practice to initialize the relations on JPA mapping.
But into web architecture (Spring MVC), where the entities will be send as JSON, usually with a RESTfull API, the relations will be omitted on the serialization and it will be fetched to the server using its path (i.e employees/[id]/projects).
If we have:
class Employee {
#ManyToMany //Employee owner of relation
protected List<Project> projects=new ArrayList<Project>(0);
}
If from the client we want to update only the Employee name, the client send the JSON to the server (HTTP PUT), it is deserialized and employee.projects will be initialized as empty collection. When the EntityManager save, it will update the properties (right) and the projects (Employee is owner side) DELETING the existing projects.
A alternative is use the DIY merge pattern. "Instead of invoking EntityManager.merge we invoke EntityManager.find to find the existing entity and copy over the state ourselves". This workaround requires specific entity code on update.
What is the best way to solve it?

Categories

Resources