How to select specific columns dynamically in a REST API? - java

I am trying to develop a REST API using Java and Spring boot. I have an entity class User.
public class User implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(name = "mobile_number")
private String mobileNumber;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "email")
private String email;
#Column(name = "created_date")
private Date createdDate;
}
My requirement is to select some specific fields from this entity. These fields can be specified
dynamically in REST API url like
http://localhost:8080/getUserDetails?start=2021-01-01&end=2021-05-05&fields=firstName
http://localhost:8080/getUserDetails?start=2021-01-01&end=2021-05-05&fields=firstName,lastName
When fields=firstName , I want to return only firstName in JSON.
Similary, firstName and lastName in JSON when fields = firstName,lastName.
If i use criteria query query.select(root.get("firstName"),root.get("lastName"))
than i have to create constructors in Entity / POJO class.
There can only be one constructor with 2 String parameters. So this approach will fail when i need to select mobileNumber and email.
If i use spring Projections than i am not able to get how to select dynamic fields in Projections without adding projections = "some value" in rest endpoint url. Also if i use interface or class projections i will have to define required fields there. Fields should be dynamic in my case.
Also i am trying to avoid fetching of all columns and than filtering it out based on requested fields as it is inefficient.
So can anyone please help me out?

Related

What is equivalent for #Formula(used in jpa), in webflux and r2dbc?

I have a firstName and lastName in my database, and I wanna make a fullname variable,
I used to set #Formula annotation in hibernate, but as I changed my services to reactive(webflux) and use r2dbc, I can't use it anymore!
my previous code was something like this:
public class OperatorUser implements UserDetails {
#Id
#Column(name = "ID")
private Long id;
#Column(name = "FIRST_NAME")
private String firstName;
#Column(name = "LAST_NAME")
private String lastName;
#Column(name = "ADDRESS")
private String address;
#Formula("FIRST_NAME || \' \' || LAST_NAME")
private String fullname;
#Formula is an Hibernate/JPA annotation and we cannot use it with R2DBC,
if we migrate from an hibernate based project to webflux, it's highly recommended to use Hibernate reactive and vert.x to have access to all hibernate annotations and facilities.
also watching the youtube video in this page help you to understand it clearly.

Nested reference object is persisting as null

I am trying to store below pojo in couchbase with spring-data, but persist json is storing "user field of type User" as null.
#JsonInclude(value = Include.NON_EMPTY)
#Document
public class ProjectXYZ {
#Id
#GeneratedValue(strategy = GenerationStrategy.UNIQUE)
private String id;
#Field
private String prjname;
#Field
private User user;
//setter and getter
}
Update:
User Pojo
#JsonInclude(value = Include.NON_EMPTY)
#Document
public class User {
#Id
#Field
private String id;
#Field
private String email;
#Field
private String firstName;
#Field
private String lastName;
//setter and getter
}
And as below I am saving it, All works fine and as expected but User object get stored as null.
ProjectXYZ project = new ProjectXYZ();
project.setUser(getUser(request));
project = projectXYZService.createProject(project);
References are not directly supported through Spring data couchbase as it needs to store meta information about the reference document id.
However there is support for fetching associated entities through N1QL ANSI Joins available in current Lovelace (3.1.x) versions. Here is the documentation for it.

How can I include references in spring rest response?

I have defined two JPARepository with spring: "Person" and "Address". I also specified a relation between Person and Address.
I can fetch all persons with:
http://localhost:8080/person/
and all address with: http://localhost:8080/address/
Also I can get the address of a single person with http://localhost:8080/person/1/address
Now I'd like to get the address to every person as a nested address when I get request: http://localhost:8080/person/
How can I include the relations in the response?
My classes as requested by #nicolasl
#Entity
public class Person {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String firstName;
private String lastName;
#OneToOne
#JoinColumn(name = "address_id")
private Address address;
//Getter/Setter here
}
#Entity
public class Address {
#Id
#GeneratedValue
private long id;
#Column(nullable = false)
private String location;
#OneToOne(mappedBy = "address")
private Person person;
//Getter/Setter here
}
Well, I guess you just can't, not using the automated rest engine provided by spring. The rest API will return links to retrieve the related entities in the "_links" section of your JSON response (you can read more about that in http://stateless.co/hal_specification.html). You'd have to call those links to retrieve your Addresses.
Another way to solve this, is implementing your own repository and assembling your own JSON response.

How to parse a list of String obtained via select box in a REST

I have this method that creates an object Event on my database by getting data from an HTML form.
#PostMapping("/events")
#Timed
public ResponseEntity<Event> createEvent(#RequestBody Event event) throws URISyntaxException {
//some code
}
My Event entity has these attributes:
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "name")
private String name;
#Column(name = "jhi_date")
private LocalDate date;
#Column(name = "attendees")
private String attendees;
#OneToOne
#JoinColumn(unique = true)
private Desk refTable;
#OneToMany(mappedBy = "event")
#JsonIgnore
private Set<CustomUser> participants = new HashSet<>();
The one that interests me is attendees. Due to my business logic I can not change its type from String to a List.
My answer is: how can I get a List of strings using a multiple select in HTML if my model doesn't have a field of type List?
I would like to receive a List from HTML and then convert it into one string.
Just to know, I am using Jhipster. Thanks in advice for your time.
This where using JHipster DTO option makes a lot of sense as the DTO will adapt Event entity data to a format easier to process by the client code.
You can enable it by editing.jhipster/Event.json to set "dto": "mapstruct", and re-generate your entity with yo jhipster:entity.

Storing nested documents in elasticsearch which may have nullable fields

I'm using elasticsearch for indexing in my application. I'm trying to store a document which in turn contains a field of a custom data structure:
#Document(indexName="sampleIndex", type="user")
class User {
#Id
private String id;
#Field(type = FieldType.Nested)
private Person person;
}
class Person {
String firstName;
String lastName;
}
I'm usingElasticsearchRepository to save this entity. There are chances that lastName or firstName of the Person may be null. In this case I get a NullPointerException on calling repository.save(entity). Is there a way to suppress this? Because I still want to save this on elasticsearch irrespective of whether some of the fields are null or not.

Categories

Resources