By default spring data does not expose #Id field in response. But my return object contains #ID value.
I have looked up online most questions are how to expose the ID field.
I can create new POJO, iterate through return objects and set only the values I need. But I'm wondering why the default behavior is not working.
If the question is how to manage entity's property and make them appear or hide in the response, then you better have to use Jackson's framework annotations. #JsonProperty("responseName") will forse a property to appear in the response with a given name, #JsonIgnore will make a property do not appear in the response.
Hope it'll help.
Related
In advance, I'm not speaking of Content Negotiation. Let's assume I've a simple JPA entity, by the way it is convertible with a related DTO it doesn't matter.
#Entity
public class User {
...
private String email;
private String password;
...
}
I've a RESTful controller with two different routes, a secured one and a public one.
#RestController
public class UserController {
...
#GetMapping("/public")
private User publicRoute() {
return service.getLatestUser();
}
#Secured("...")
#GetMapping("/private")
private User privateRoute() {
return service.getLatestUser();
}
}
For both routes the same entity is returned, but in the first case a public representation, let's say for a user profile, without sensitive stuff like E-Mail and Password should be returned. However in the second case a private representation, let's say for the owner itself, is required.
Is there any elegant way for doing this? I tried it on JSON level with #JsonIgnore but it doesn't worked for me. Also I tried to use Response-Objects, but it results in a lot of boilerplate code! Any suggestions?
See Also:
Recommended by Ananthapadmanabhan there already exists some questions/resources about this topic:
Spring REST webservice serializing to multiple JSON formats
How do I serialize using two different getters based on JsonView in RestController?
You could have different DTO objects being returned from the two endpoints instead of returning the same Entity class, that way you can have control over which attributes should be there in the response.
Read here about the advantages of using a DTO .
Another approach that you could make is to have custom serializers and deserializers for your endpoint.
You could read here for more details.
And here
Ignore dto fields while sending back to controller.
you can write you own method if your object is not final
private User ignoreEmailAndPass(User user){User usr=new User();usr.setName();//send only required fields.}
from Question:
In the database table you can have two roles
Say like User and Owner
3.In the service,check if it is user or owner and get the required details then have the
two DTOs,for each of their information that you want to send,set the info and return.
Or have a Common DTO, conataining all the information and when want to send user info just ignore the other info{Subset} else all.
Tell me what do you think of this solution?
I'm working on a spring boot project nowadays. And I totally love it.
I've created my services, entities, repos. Everything seems ok for simple scenarios.
But the thing is , one of my entities has attributes(properties) as follows:
userID;
loginName;
email;
profiles;
createdDate;
lastModifiedDate;
I'm listing my services on swagger ui. When I try to call update service on swagger, lastModifiedDate criteria shouldn't be listed as an input property, I need to handle this property on the back end. Likewise, when I try to add a new user record from swagger, createdDate criteria shouldn't be listed as an input property, I need to handle this property on the back end.
I try to google this, but I couldn't find a relative answer so far.
Do you have any recommendations ? Any links, documents. . .
Or is it even possible ?
screenshots from swagger-ui :
https://ibb.co/QMWDLjR
https://ibb.co/yqqQWyG
It's a good practice to separate entity and api resonse object. That way you can choose what fields to expose to api contract.
So in your case, create a new object without modifedOn and createdOn and use that in your controller
I have a simple persistent pojo like:
public class Peristent {
private String unsafe;
}
I use Spring Data mongoTemplate to persist and fetch the above object. I also need to encrypt the Persistent.unsafe variable and store a complex representation of that in backend, everytime I try to save Persistent object.
Can I annotate Persistent, or provide some sort of hooks where I can make the aforementioned translations without me having to do that in the Pojo code manually. This has to happen automatically during mongoTemplate.insert.
Spring Data currently only support Type based conversions. There is an issue for supporting property based conversion, which you might want to track.
Therefore annotating won't work. What you could do is, create use a separate class for the property, which just wraps the String and register a custom converter for that type. See http://docs.spring.io/spring-data/data-mongo/docs/1.10.4.RELEASE/reference/html/#mongo.custom-converters for details, how to do that.
I have an #Entity that has a field owner:
#Entity
#EntityListeners({TalkListener.class})
public class Talk {
private #ManyToOne(targetEntity = User.class, optional = false) User owner;
// ...
}
Note: I have a listener in place that implementes #PrePersist. From what I have read it is discouraged to lookup request parameters from there (maybe it is also impossible, I didn't go on researching in this direction). There is the section about events in the docs, but it also seems purely entity-related and not taking the context of the request into account.
I would like to infer the owner from the authenticated user that POSTs the request. What is the easiest way to do so? If it is necessary to override the POST a snippet or linked example would be much appreciated.
Update 1:
#NeilMcGuigan suggested using Spring Data JPA's auditing features, which include a #CreatedBy annotation that would clearly solve the original question (and I would accept it as an answer).
Update 2:
A good tutorial about auditing with Spring Data JPA as well as an alternative of getting the principal within entity lifecycle events can be found here.
For educational purpose, what would be another way if I needed to access some value from the request to populate a value in my entity (say my current use case wasn't #CreatedBy but something different)?
I want to make flexible database design for a Spring-mvc application, I mean that I want for example let user delete or add some attributes on the application withou disturbing it.
For example:
User want to add "adress mail" to his costumer or he want to delete "postal code" because he don't need this information ...etc
Something like that.
Is any body has an idea how to make that?
Use schemaless database, for example MongoDB. With Spring Data MongoDB you can persist maps that will give you flexibility you need:
#Document
public class Customer{
#Id
private ObjectId id;
private Map<String, String> properties;
...
}
Even though it is doable, I am not convinced if your design is valid. You can persist custom attributes in DB, but showing them in GUI at some point, when you need to customize look and feel for particular field it can become quite frustrating issue.