I have a DTO with two entity. How can I validate these entities?
What annotation should I use?
I use rest api, JSON, spring boot.
I know how to validate one entity. But I don't know what to do with DTO.
#PostMapping
public ResponseEntity<?> create(#Valid #RequestBody DTOClient client) {
....
return responseEntity;
}
public class DTOClient{
//What I should use here to validate these entities?
private Client client;
private Skill skill;
}
#Entity
public class Client{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String first_name;
private String last_name;
}
#Entity
public class Skill{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private int year;
}
Use javax.validation for the fields which you want to validate. Below code is an example to validate first_name in client object should not null or blank.
#PostMapping
public ResponseEntity<?> create(#Valid #RequestBody DTOClient client) {
....
return responseEntity;
}
public class DTOClient{
//What I should use here to validate these entities?
#Valid
#NotNull(message="client should not null")
private Client client;
private Skill skill;
}
#Entity
public class Client{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#NotBlank(message="first name of client should not be null or blank")
private String first_name;
private String last_name;
}
#Entity
public class Skill{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private int year;
}
In short, you need use #Valid for Bean, like controller methods' params and the fields which not primary. And Constraint annotations for the fields which need validate.
Related
i am new in spring boot and i could not find solution for this for a day now.
#GetMapping used to retrive item gives a responce of infinite loop of foreignkey object "user".
why am i getting this infinite loop?
how to fix it?
user object in infinite loop(the problem)
result that i want
item entity
#Entity
public class Item{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long ItemId;
#ManyToOne
#JoinColumn(name = "owner_id")
private User user;
private String ItemName;
// #Column(columnDefinition="text")
private String Description;
private double Price;
private int AvailableQuantity;
private double shippingWeight;
// #Transient
// private MultipartFile Picture;
#Enumerated(value = EnumType.STRING)
private Category category;
#OneToMany(mappedBy = "item")
#JsonIgnore
private List<CartItem> CartItemList;
}
user entity
#Entity
#Table(name = "Utilisateur")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idU;
private String username;
private String password;
private String firstname;
private String lastname;
private String gender;
private Long phone;
private String adress;
#Temporal(TemporalType.DATE)
private Date dateofbirth;
private int rating;
private String email;
public Role role;
private Integer status;
#OneToMany(mappedBy = "user")
private List<Item> ItemList;
}
item service
#Service
public class ItemService implements ItemServiceInterface{
#Autowired
ItemRepository itemrepository;
public Optional<Item> getItemById(long id){
return itemrepository.findById(id);
}
}
item controller
#RestController
public class ItemControl {
#Autowired
ItemServiceInterface itemservice;
#GetMapping("/getitem/{id}")
public Optional<Item> getitembyid(#PathVariable Long id) {
return itemservice.getItemById(id);
}
}
You can use combination of #JsonManagedReference and #JsonBackReference to discourage Jackson from infinite serialization.
#Entity
#Table(name = "Utilisateur")
public class User {
// omitted
#JsonManagedReference
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<Item> ItemList;
}
#Entity
public class Item{
// omitted
#JsonBackReference
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "owner_id")
private User user;
}
More details could be found here https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion
You can make use of lazy loading to cut the dependency loop between user and item. However, following that approach might potentially affect other parts of your projects because other codes might use the entity with an assumption that item list in user entity is already eager fetched.
A better way is not return the entity object directly to the REST response. You can define a data model for the rest response and convert the entity to that model in your service class. This way, you can completely control what to return and not to.
Another approach if you still want to use the entity as response: https://www.baeldung.com/spring-data-jpa-named-entity-graphs. This way, you can define when to use the lazy load with each specific query.
I have two classes:client and contant.Each client can have many contacts.the structure of client class is
public class client{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long clientId;
private String clientName;
#OneToMany
#JsonBackReference
private List<ContactInfo> contactInfoList;
//default constructor
//getter and setter
}
and the contact class is :-
#Entity
public class ContactInfo {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long contactId;
#NotNull
private String mobilePhone;
#ManyToOne
#JsonManagedReference
private Client client;
//default constructor
//getter and setter
}
And the classes to fetch data are:-
public interface ContactInfoRepo extends JpaRepository<ContactInfo,Long> {
}
public interface clientRepo extends JpaRepository<client,Long> {
}
public class ClientController {
#Autowired
ClientRepo repo;
#RequestMapping(method = RequestMethod.POST, path = "api/client")
public void addClient(#RequestBody Client client)throws
ConstraintViolationException {
System.out.println(client.toString());
repo.save(client);
}
}
this is the json data I want to save in two different tables;
{
"clientName":"test",
"contactInfoList":[{"mobilePhone":"1234"},{"mobilePhone":"12345"} ]
}
I want the contactInfoList to be stored in contact table and the clientName in client table.I am using JPA in spring Boot .When I send the json value the contactInfoList is null.Could someone please help on this?
So lets say I have User object like this
#Entity
public class User {
#Id
#GeneratedValue
private long id;
private String name;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "address", referencedColumnName = "id")
private Address address;
}
#Entity
public class Address {
#Id
#GeneratedValue
private long id;
private String city;
private String country;
}
Now I don't want to write validation annotations in entities. What I would like to do is validate User in #RestController like this
#RestController
public class InvoiceController {
#RequestMapping(value="/users/add", method = RequestMethod.POST)
public Invoice addInvoice(#Validated #RequestBody ValidUser user) {
... do stuff
}
}
The validation annotations would be in ValidUser being like this.
public class ValidUser extends User {
#NotNull
private String name;
#Valid
private Address address;
}
public class ValidAddress extends Address{
#NotNull
private String city;
#NotNull
private String country;
}
The validation works when I remove the address field from the ValidUser but not when it is there. How can I make address validation also work?
I have 2 classes.
User class
#Entity("user")
public class User {
#Id
ObjectId id;
String companyName;
String email;
private byte[] image;
}
Ticket class: ownerId reference to 'user' table
#Entity("ticket")
public class Ticket {
#Id
private ObjectId id;
private ObjectId ownerId;
}
I want to fetch users that is ticket's owner. What is the best way to do that with Morphia?
#Entity("ticket")
public class Ticket {
#Id
private ObjectId id;
#Reference
private User user;
}
So whenever you fetch a ticket, you can directly access the user.
I have class User:
#Entity
public class User {
#Id
#GeneratedValue
private Integer id;
private String name;
private String password;
#ManyToMany
#JoinTable
private List<Role> roles;
}
Class Owner inherits from User
#Entity
public class Owner extends User {
private String pesel;
private String adress;
#OneToMany(cascade={CascadeType.PERSIST, CascadeType.REMOVE})
private List<Pet> pets;
}
and Owner had Pet
public class Pet {
#Id
#GeneratedValue
private Integer id;
private String name;
private String weight;
#ManyToOne
private Owner owner;
}
Why when starting the application gets the error:
org.springframework.data.mapping.PropertyReferenceException: No
property user found for type Pet!
--EDIT
First I have version, which was as follows:
now I try to share User instance to a doctor and the owner of the animal
The problem is that I do not know whether I am doing the mapping , and therefore wanted to ask whether it must look like
--edit2
I've simplified the scheme just a bit to better illustrate what happens
--edit3
Currently my Object's was presented:
#Entity
public class Pet {
#Id
#GeneratedValue
private Integer id;
private String name;
private String weight;
}
User
#Entity
public class User {
#Id
#GeneratedValue
private Integer id;
private String name;
private String password;
#ManyToMany
#JoinTable(name="user_roles")
private List<Role> roles;
}
PetOwner
#Entity
public class PetOwner extends User {
private String pesel;
private String adress;
#OneToMany(mappedBy="petOwner")
private List<Pet> pets;
}
I replace
#ManyToOne
private PetOwner petOwner;
for
#ManyToOne
private Owner petOwner;
and it works. Do you have a PetOwner class?
Also provide the log error to get more information about it