How to build nested object using criteriaBuilder.construct in JPA Criteria Query - jpa

I want to query the list of the phone with the person as a phone DTO object but while I construct a DTO object it provides an error.
Phone Entity:
public class Phone {
#Id
#GeneratedValue
private Long id;
private String number;
#Enumerated(EnumType.STRING)
private PhoneType type;
#ManyToOne
#JoinColumn(name = "person_id")
private Person person;
}
Person Entity:
public class Person {
#Id
#GeneratedValue
private long id;
private String name;
private String nickName;
private String address;
private LocalDateTime createdAt;
#Version
private int version;
#OneToMany(mappedBy = "person" cascade = CascadeType.ALL)
private List<Phone> phones;
}
Phone DTO:
public class PhoneDTO {
private Long id;
private String number;
private PhoneType type;
private PersonDTO person;
}
Person DTO:
public class PersonDTO {
private long id;
private String name;
private String nickName;
private String address;
private LocalDateTime createdAt;
private int version;
}
Criteria query:
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<PhoneDTO> criteriaQuery = builder.createQuery(PhoneDTO.class);
Root<Phone> root = criteriaQuery.from(Phone.class);
Join<Phone, Person> person = root.join("person");
Path<Object> id = root.get("id");
Path<Object> number = root.get("number");
Path<Object> type = root.get("type");
Path<Object> personId = person.get("id");
Path<Object> name = person.get("name");
Path<Object> nickName = person.get("nickName");
Path<Object> address = person.get("address");
Path<Object> createdAt = person.get("createdAt");
Path<Object> version = person.get("version");
criteriaQuery.select(builder.construct(PhoneDTO.class, id, number, type, builder.construct(PersonDTO.class, personId, name, nickName, address, createdAt, version)));
TypedQuery<PhoneDTO> query = em.createQuery(criteriaQuery);
How to do this??
criteriaQuery.select(builder.construct(PhoneDTO.class, id, number, type, builder.construct(PersonMediumDTO.class, personId, name, nickName, address, createdAt, version)));
How to construct a nested object??

Related

Why is there a loop in #OneToMany mapping?

I am trying to create a #OneToMany database using JPA. There is a object Flight and a object Passenger.
the code:
#Entity
#Table(name = "passengers")
public class Passenger {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "name")
private String name;
#Column(name = "surname")
private String surname;
private String email;
private String phoneNumber;
private String birthDate;
#ManyToOne(optional = false)
#JoinColumn(name = "flight_id")
private Flight flight;
public Passenger() {
}
public Passenger(String name, String surname, String email, String phoneNumber, String birthDate, Flight flight) {
super();
this.name = name;
this.surname = surname;
this.email = email;
this.phoneNumber = phoneNumber;
this.birthDate = birthDate;
this.flight = flight;
}
#Entity
#Table(name = "flights")
public class Flight {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "flight_id")
private long id;
private String departure;
private String destination;
private String date;
private int capacity;
private float price;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "flight", cascade = CascadeType.ALL)
private Set<Passenger> passengers;
public Flight() {
}
public Flight(String departure, String destination, String date, int capacity, float price) {
super();
this.departure = departure;
this.destination = destination;
this.date = date;
this.capacity = capacity;
this.price = price;
}
this is how I add a new Passenger:
#PostMapping("/flights")
public ResponseEntity<Object> updateFlight(#RequestBody Flight flight) {
long id = flight.getId();
Optional<Flight> flightOptional = flightRepository.findById(id);
if (!flightOptional.isPresent())
return ResponseEntity.notFound().build();
int currentCapacity = flight.getCapacity();
flight.setCapacity(currentCapacity - 1);
for(Passenger passenger : flight.getPassengers()) {
System.out.println(passenger.getName());
}
this.flightRepository.save(flight);
return ResponseEntity.noContent().build();
}
Unfortunately, when I map the flights and passengers, I appear to have a never ending loop. Passengers have the details of the flight and passengers and again flight and then passengers, and so on.
Is there any way I can resolve it? Am I missing anything?
To avoid the cyclic problem Use #JsonManagedReference, #JsonBackReference as below.
Add #JsonManagedReference on Parent class
#JsonManagedReference
#OneToMany(fetch = FetchType.EAGER, mappedBy = "flight", c
ascadee = CascadeType.ALL)
private Set<Passenger> passengers;
Add #JsonBackReference on child class as below
#JsonBackReference
#ManyToOne(optional = false)
#JoinColumn(name = "flight_id")
private Flight flight;

Spring Boot : Building object Rest API

I created 4 classes for 3 tables. Those tables are built to store orders with products.
My first entity is orders :
#Entity
#Table(name="orders")
public class OrderEntity implements Serializable {
...
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
#ManyToOne(fetch = FetchType.LAZY)
private UserEntity seller;
private String paymentMode;
private double totalAmount;
#OneToMany(mappedBy = "pk.order")
private List<OrderProductEntity> orderProducts;
#DateTimeFormat
private Date createdAt;
...
}
My second entity is products:
#Entity
#Table(name="products")
#Getter #Setter
public class ProductEntity implements Serializable {
...
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
#Column(nullable = false)
private String productKeyId;
#ManyToOne
#JoinColumn(name = "category_id")
private CategoryEntity category;
#Column(nullable = false)
private String name;
#Column(nullable = false)
private double price;
#Column(nullable = false)
private int availableQty;
#JsonManagedReference
#OneToMany(mappedBy = "pk.product", fetch = FetchType.EAGER)
#Valid
private List<OrderProductEntity> orderProducts;
...
}
I also define the pivot table in the OrderProductEntity:
#Entity
#Table(name="order_product")
#Getter #Setter
public class OrderProductEntity {
#EmbeddedId
#JsonIgnore
private OrderProductPK pk;
#Column(nullable = false)
private Integer quantity;
// default constructor
public OrderProductEntity(){}
public OrderProductEntity(OrderEntity order, ProductEntity product, Integer quantity) {
pk = new OrderProductPK();
pk.setOrder(order);
pk.setProduct(product);
this.quantity = quantity;
}
}
And I defined the PK of this table :
#Embeddable
#Getter #Setter
public class OrderProductPK implements Serializable {
#JsonBackReference
#ManyToOne(optional = false, fetch = FetchType.LAZY)
#JoinColumn(name = "order_id")
private OrderEntity order;
#ManyToOne(optional = false, fetch = FetchType.LAZY)
#JoinColumn(name = "product_id")
private ProductEntity product;
}
Now my issue is to return the data to the front office by a web service Rest.
I created a model that represent what i want to obtain as result.
public class OrderRest {
private String orderKeyId;
private String paymentMode;
private double totalAmount;
private List<ProductRest> orderProducts;
private UserRest seller;
private Date createdAt;
}
And :
public class ProductRest {
private String productKeyId;
private String name;
private double price;
private int qty;
private String imgPath;
private CategoryRest category;
}
In my controller i want to return an OrderRest object :
public List<OrderRest> getOrders() {
List<OrderRest> returnValue = new ArrayList<>();
List<OrderDto> orderDtos = orderService.getOrders();
// loop the result
for (OrderDto orderDto : orderDtos) {
OrderRest orderRest = new OrderRest();
ModelMapper modelMapper = new ModelMapper();
orderRest = modelMapper.map(orderDto, OrderRest.class);
returnValue.add(orderRest);
}
return returnValue;
}
THis method map the List of OrderRest and call the service layer :
public List<OrderDto> getOrders() {
List<OrderDto> returnValue = new ArrayList<>();
Iterable<OrderEntity> orderEntities = orderRepository.findAll();
ModelMapper modelMapper = new ModelMapper();
for(OrderEntity orderEntity: orderEntities) {
OrderDto orderDto = new OrderDto();
UserDto userDto = orderDto.getSeller();
List<OrderProductDto> orderProductDtos = orderDto.getOrderProducts();
orderDto = modelMapper.map(orderEntity, OrderDto.class);
returnValue.add(orderDto);
}
return returnValue;
}
With OrderDto :
public class OrderDto implements Serializable {
#Getter(AccessLevel.NONE)
#Setter(AccessLevel.NONE)
private static final long serialVersionUID = 1L;
private Long id;
private String orderKeyId;
private String paymentMode;
private double totalAmount;
private List<OrderProductDto> orderProducts;
private UserDto seller;
private Date createdAt;
}
And OrderProductDto :
public class OrderProductDto implements Serializable {
#Getter(AccessLevel.NONE)
#Setter(AccessLevel.NONE)
private static final long serialVersionUID = 1L;
private String productKeyId;
private String name;
private Integer price;
private Integer qty;
private String imgPath;
private CategoryDto category;
}
My issue is concerning what i return from the REST API :
my product list returns nothing :
"orderProducts": [
{
"productKeyId": null,
"name": null,
"price": 0.0,
"qty": 0,
"imgPath": null,
"category": null
},...
]

Project data from different tables to a model

I defined my model classes like below.
#Entity
#Table(name = "my_employee")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
#OneToMany(cascade = CascadeType.ALL)
#JoinTable(name = "emp_address_mapping", joinColumns = #JoinColumn(name = "emp_id"), inverseJoinColumns = #JoinColumn(name = "address_id"))
private List<Address> addresses = new ArrayList<Address>();
.......
.......
}
#Entity
#Table(name = "my_address")
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String country;
.....
.....
}
public class EmployeeDetails {
private int empId;
private String name;
private String country;
......
......
}
How can I write a query using #Query annotation to populate all the EmployeeDetails.
public interface EmployeeRepository extends CrudRepository<Employee, Integer> {
#Query("SELECT new com.sample.app.model.EmployeeDetails......")
List<EmployeeDetails> getEmployeeDetails();
}
Create the constructor in EmployeeDetails
public EmployeeDetails(int id,String name,String country){
this.id=id;
this.name=name;
this.country=country;
}
Try this query
To get all employee details:
SELECT new com.sample.app.model.EmployeeDetails(e.id,e.name,a.country) from Employee e,Address a

JPA query with OneToOne lazy

I have this structure of object
#Entity
public class Member {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long memberId;
private String name;
private boolean man;
private String address;
#OneToOne(fetch = FetchType.LAZY)
private City city;
private String postalCode;
private String phone1;
private String phone2;
private LocalDate birthdate;
private String email;
private String emergencyContactName;
private String emergencyPhone;
private String paymentGatewayKey;
#OneToMany(fetch = FetchType.LAZY)
private List<Contract> contracs;
#OneToOne(fetch = FetchType.LAZY)
private Commerce commerce;
}
#Entity
public class Contract {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long contractId;
private BigDecimal price;
private int frequency;
private int term;
private LocalDate startDate;
private LocalDate endDate;
private int numberOfPayment;
#Enumerated(EnumType.STRING)
private StatusEnum status;
#OneToMany(fetch = FetchType.LAZY,mappedBy = "contract")
private List<Payment> payments;
#ManyToOne
private Member member;
}
#Entity
public class Payment {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long paymentId;
private BigDecimal price;
private LocalDate date;
#Enumerated(EnumType.STRING)
private StatusEnum status;
#Enumerated(EnumType.STRING)
private PaymentModeEnum paymentMode;
#ManyToOne
private Contract contract;
#OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.MERGE, CascadeType.PERSIST})
private List<Operation> operations;
}
is it possible from a member query to get only the needed contract, payment, city and commerce info?
If member have many contract... i want to get only contract #2...
I started this query but city and commerce are lazy and i don't know what to do with theses fields.
select m from Member m inner join fetch m.contracs c inner join fetch c.payments p where c.contractId = :contractId

How to select an attribut that is on the "wrong" side of a OneToOne unilateral relationship with JPA criteria

I've 2 entities:
#Entity
public class Customer{
#Id
#Column(name = "ID")
private Long id;
#OneToOne(mappedBy = "customer")
private Address address;
#Column(name = "FIELD_1")
private String field1;
#Column(name = "FIELD_2")
private String field2;
}
#Entity
public class Address{
#Id
#Column(name = "ID")
private Long id;
#OneToOne
#JoinColumn(name = "CUST_ID")
private Customer customer;
}
If I do a select to retrieve the Customer, the Adress is retrieved as well, all good.
But I want to do a projection and build a DTO, so only select field1 and field2 along with the Adress entity.
public class MyDTO {
private String field1;
private String field2;
private Address address;
public MyDTO (String pField1, String pField2, Adress pAddress){
field1 = pField1;
field2 = pField2;
adress = pAddress;
}
}
So I've coded that DAO method :
public List<MyDTO > getListMyDTO() {
CriteriaQuery<MyDTO > crit = builder.createQuery(MyDTO .class);
Root<Customer> root = crit.from(Customer.class);
// This is to avoid a inner join since some customer may not have an adress and i dont want to exclude them from my select
root.join("address", JoinType.LEFT);
crit.multiselect(root.get("field1"), root.get("field2"), root.get("address"));
return em.createQuery(crit).getResultList();
}
em being the entity manager.
However that doesn't work and the address ends up always null.
I sorta understand this as there is no field from root pointing to the address table, but since it works when i do a select on the entity instead of a DTO, there must be a way to make this work no?