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

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);

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
}
}

how to validate spring model object with different attribute requirements different method calls?

we are using single model class in spring controller say
Student(id,firstname,lastname);
Now my controller have two methods
get student details where we pass Student object with id only.(only Id require)
update student details with all details id,firstname,lastname (where we use id for reference to update names)
in both controller methods I want to use spring validator so how can I write validated method for both controller methods as I required only id attribute to get student details and in other I want all three attributes to updated student details.
we are not using spring boot.
I always use dtos (data transfer Objects) for models that are sent by the client and separate models for responses.
That has many advantages. The incoming api models are decoupelt from the models that are used in your application. In addition, with the dto you just provide a model with the minimum of attributes a client may send to the api. And to adress your question you can verify them separatere.
I don‘t think you want your client to update the students id. So for your model use a dto that has the same attributes like a full student object but without the id Field.

How can I insert data into the database when an entity is created?

I'm creating a website for a school project which uses spring for the backend. I'm trying to insert data into the database when new data is saved to a specific table.
I've tried using #HandleAfterCreate and #PrePersist, but neither worked. I'm not very experienced with spring. The teacher told us to use it and now I don't know what do.
#HandleAfterCreate
public void handlePersonBeforeCreate(Person person){
logger.info("Inside Person Before Create....");
Set<Qualifikation> qualifikationen = new HashSet<>();
kompetenzRepository.findAll().forEach(kompetenz -> {
Qualifikation qualifikation = new Qualifikation();
qualifikation.setAusmass(0);
qualifikation.setKompetenz(kompetenz);
qualifikation.setPerson(person);
});
person.setQualifikationen(qualifikationen);
System.out.println(person.getDisplayName());
}
The code should set a person's "Qualifikation" to a default value when the person is inserted (via OAuth login). It should have every "Kompetenz" with a value of 0 by default. Kompetenz has a 1 to n relation to Qualifikation. If you need more information please ask me.
It looks like you're trying to have access to the repository layer of your application inside an entity. This is generally not a good idea, as the entities should only know about the data they hold, not the other application components.
In this particular case it would be wise to use a #Service class with a method that you can call to insert the data into the database. In the method you could then insert any other entities as well. Let your repositories be fields of the service and make them #Autowired.
I think you need to enable JPA auditing . It can be enabled in Spring by add #EnableJpaAuditing to your persistence configuration. This tells Spring to listen JPA entity lifecycle events and call the annotated methods in appropriate places.
Also I think you should make the callback method private if it is meant to be called only when persisted (#PrePersist).
See details here. In this article is also presented entity listeners which might also be a good solution when dealing with multiple entities having a need for same pre-persist functionality.
I think you should create a service class, a repository class and an entity which will be stored through repository. The logic of getting all inner elements and filling it with default value is to be written in service and not a good idea to write in entity class.
If you need any help regarding it, let me know .
Welcome to community!!

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

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

Categories

Resources