Dozer mapper field don`t exists - spring-boot

I trying to user Dozer in my app, so I have 2 classes:
public MyEntity{
private String name;
private Stirng age;
private String user;
private Integer day;
}
public class MyVO{
private String name;
private String age;
}
So, first I read the Entity from my db(with all fields filled) then I call the dozer to copy the values from VO to Entity
MyEntity entity = myRepo.findById(1);
entity = mapper.map(myVo, MyEntity.class);
but dozzer first sets null to all props in myEntity and then copy the values from myVo,
It`s possible to keep that props (who does not exist in both object) and copy only that fields that exists(or are mapped in my .xml) file

mapper.map(myVo, MyEntity.class);
This call to Dozer tells it to create a new MyEntity instance and then map the values from myVo. This is why some of your fields are null in the resulting entity.
If you want to update an existing instance using Dozer, call Dozer with the instance instead of the class name, i.e.
mapper.map(myVo, entity);
Note, this does not return the entity back to you since it modifies it in place.

Related

Advantage of assigning the returned savedEntity in Spring Data

I see in most of the coders save data(using spring data) as:
savedEntity = repo.save(savedEntity);
Long id = savedEntity.getId();
I am confused about why most of them assign back the returned value to the saved Entity while the following code also works exact(I have tested myself):
repo.save(savedEntity);
Long id = savedEntity.getId();
Did I miss some benefit of assigning back?
for example, let the entity be:
#Entity
public class SavedEntity {
#Id
private int id;
private String name;
//getter, setters, all arg-constructor, and no-arg constructor
}
Consider the object of SavedEntity is
SavedEntity entity = new SavedEntity(1,"abcd");
now for your first question,
SavedUser entity1 = repo.save(entity);
Long id = entity1.getId();
this entity1 object is the return object getting from the database, which means the above entity is saved in the database succesfully.
for the Second Question,
repo.save(entity);
Long id = entity.getId();//which you got it from SavedEntity entity = new SavedEntity(1,"abcd");
here the value of id is the integer you mentioned in place of id(the raw value).
Most of the time the id (primary key) is generated automatically while storing the entity to the database using strategies like AUTO, Sequence etc. So as to fetch those id's or autogenerated primary key values we assign back the saved entity.
For example:
#Entity
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
}
In this case you'll not pass the id externally but it will create a value for it automatically while storing the data to DB.

How do I get Spring's Data Rest Repository to retrieve data by its name instead of its id

I am using Spring Data's Rest Repositories from spring-boot-starter-data-rest, with Couchbase being used as the underlining DBMS.
My Pojo for the object is setup as so.
#Document
public class Item{
#Id #GeneratedValue(strategy = UNIQUE)
private String id;
#NotNull
private String name;
//other items and getters and setters here
}
And say the Item has an id of "xxx-xxx-xxx-xxx" and name of "testItem".
Problem is, that when I want to access the item, I need to be accessible by /items/testItem, but instead it is accessible by /items/xxx-xxx-xxx-xxx.
How do I get use its name instead of its generated id, to get the data.
I found out the answer to my own question.
I just need to override the config for the EntityLookup.
#Component
public class SpringDataRestCustomization extends RepositoryRestConfigurerAdapter {
#Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.withEntityLookup().forRepository(UserRepository.class).
withIdMapping(User::getUsername).
withLookup(UserRepository::findByUsername);
}
}
Found the info here, though the method name changed slightly.
https://github.com/spring-projects/spring-data-examples/tree/master/rest/uri-customization
If you want query the item by name and want it perform as querying by id,you should make sure the name is unique too.You cant identify a explicit object by name if all objects have a same name,right?
With jpa you could do it like:
#NotNull
#Column(name="name",nullable=false,unique=true)
private String name;

Javers compare entity to DTO

i'm new to Javers, and i`m currently using it to create a patch update for my entity. But i'm having some struggle with one specific scenario
I want to compare a Entity against a EntityDTO/VO and get only the changes in values, the current comparison only returns that is a NewObject and ObjectRemoved changes.
Example:
public class Entity{
private ObjectId id;
private String name;
private String description;
}
public class EntityDTO{
private String name;
}
//
Entity oldState = new Entity(new ObjectId(), "oldName" , "oldDescription);
EntityDTO newState = new EntityDTO( "newName" );
JaversBuilder.javers().build().compare(oldState, newState).getChanges();
//This is returning only NewObject/ObjectRemoved changes, and the intended is to be ValueChange/ReferenceChange
The questions is, is there a way to compare only the similar attributes between the objects?
No, in JaVers, you can compare only objects of the same type.

Spring Boot map single JSON to two entities

A single JSON is posting from Postman and having two entity names as employee and employee address. From that JSON, empName should be stored in first entity and empAddress should be stored in second entity.
How to do this in Spring Boot? I tried to write only Entities.
First Entity:
class Employee{
private int emId;
private String empName;
//Getters;
//Setter;
}
Second Entity:
class EmployeeAddress{
private int emId;
private String empAddress;
//Getters;
//Setter;
}
My JSON: the firt value in JSON need to be stored in first entity and second need to be stored in second entity. How to do this in Spring Boot from controller?
{
"empName": "sam",
"empAddress:"chennai"
}
You need a DTO.
Something like this:
class Employee{
private String empName;
private String empAddress;
}
So, you can return this object as a Json

Spring Data Rest save record with relation (foreign-key) in Java (repo.save())

I don't know how to save a record in SDR with a link to an existing table.
For example:
There is a lookup-table Flag and another table Account with name and n:1 relation to Flag-ID.
The IDs in Flag-table are already created.
#Entity
public class Account{
public Account(String name, Flag flag){
this.name = name;
this.flag = flag;
}
#Id
private int id;
#Column
private String name;
#ManyToOne
private Flag flag;
// Getter & Setter
}
#Entity
public class Flag{
public Flag(String title){
this.title = title;
}
#Id
private int id;
#Column
private String title;
// Getter & Setter
}
Now I want to add an account and link it to the flag-id like this:
AccountRepo accountRepo;
accountRepo.save(new Account("Name", 0));
But I declared an object in my account-function and if I want to execute the save-function, I have to add a flag-object like this:
accountRepo.save(new Account("Name", new Flag("title")));
However in this case, the framework will add a new Flag-record, what I don't want. I only want to link it.
So I need help for solving my problem.
Thanks!
Edit:
The two answers from #piotr-sołtysiak and #upesh-m helped and worked for me. Thanks for your help!
You can use 'merge' of hibernate, ie. entityManager.merge(new Account("Name", new Flag("title"))). But the Id of the Flag should be an existing Id , so that it just adds an entry to Account.
ie. If you already have a flag record existing in db with id = 1, and you want to add an account linked to this flag, then use entityManager.merge(new Account("Name", existingFlagObject)
Find desired flag entity using dedicated repository, e.g
Flag flag = flagRespository.findByTitle("title");
Set it in Account entity and save:
accountRepo.save(new Account("Name", flag));

Resources