Filter ChildEntites in jpa specifiction - spring-boot

I am using JPA specs for searching of orders but inside my order Entity there is an another property ProductEntity which is a list. there is a another property ProductType inside my ProductEntity. now i need to filter my productList inside my orderEntity on the basis of productType That i will send in RequestParam of my api..
1.here is my parent Entity
OrderEntity{
private String tgxId;
private List<ProductEntity> products;
}
2.here is my ChildEntity
ProductEntity{
private String id;
private String orderId;
ProductType type;
}
now , when i do search orderslist i also need to filter my product list in the basis of ProductType that i send from RequestParam.
Result should contains entire order object list but products list inside each orderEntity should be filtered on the basis productType that i will send form RequestParam.
Thanks.

Related

Dynamic Filter, Hibernate

I have this entity model. I would like to filter the mapped association Client-Product with a parameter "ISIN";
I've tried:
#FilterDef(name="filterIsin", parameters ={#ParamDef(name="insinList" ,type ="string")})
#Filter(name="filterIsin", condition = "ISIN in (:insinList))
...
Filter filter = entityManager.unwrap(Session.class).enableFilter("filterIsin");
filter.setParameterList("insinList, ...");
But I don't get the filtered collection. As you can see the relation is Lazy, when I get the data with Hibernate.initizlize() the collection is not filtered.
in which entity do i need to define the filter?
Is there any problem with Lazy?
Client
...
#OneToMany(fetch=FetchType.LAZY)
#Fetch(FetchMode.SUBSELECT)
#JoinColumns(...)
private List<PiProduct> products;
PiProduct
...
#ManyToOne
#JoinColumns(...)
private Product product;
Product
...
#Column(name=ISIN)
private String isin;
#OneToMany(mappedBy = "productos")
private List<PiProduct> piProducts;
...
The collection of clients with the products filtered by isin

Spring Mongodb $filter nested object using CriteriaDefinition

I have the following classes
#Document("artists")
public class Artist {
private String name;
private List<Album> discography;
// Getters and Setters
}
public class Album {
private String title;
private Instant releaseDate;
// Getters and Setters
}
My goal is to write an Aggregate function using Spring data mongodb that will allow me to first find an Artist by name, then look through the associated List<Album> and filter its contents based on a date range provided. It should then return a List<Album> with all the instances of Album that fell within that date range.
The main problem I'm having is that an instance of CriteriaDefinition is provided, and I need to construct the Aggregation and $filter conditions using the contents of it.
// A CriteriaDefinition gets passed into this method
// which contains various criteria to search on
Aggregation agg = Aggregation.newAggregation(
Aggregation.match(criteriaDefinition), //This returns the correct Artist, but with all Album objects
Aggregation.project()
.and(filter("album.discography")
.as("discography")
.by( //how do use a CriteriaDefinition here? )
.as("albums")
);
List<Album> albums = mongoTemplate
.aggregate(agg, Artist.class, Album.class);
return albums;
Is it even possible to filter on CriteriaDefinition?
You can use unwind operator with a match on subdocuments. For example i filtered artists with name "foobar" and returned its albums with a releaseDate greater than now.
Please try :
Aggregation aggregation = newAggregation(
match(where("name").is("foobar")),
unwind("discography"),
match(where("discography.releaseDate").gt(new Date())));
AggregationResults<Album> results = mongoTemplate.aggregate(aggregation, Artist.class, Album.class);
List<Album> albums = results.getMappedResults();

Spring- How to remove a property from a list of Objects?

I have an Entity "Person" which has following properties,
Id
Name
F-Name
Age
Address
When I call a repository function findAll() on Person, it returns a list of Persons.
List<Person> list = somefuntionToConvertIterableToList(personRepository.findAll());
this list has multiple objects of Person Type.
Person ...... Id1,Name1, F-Name1, Age1, Address1
Person .......IdN,NameN, F-NameN, AgeN, AddressN
I need to remove "Id" from all Persons, what should I do?
I know we can use "remove" to delete an element of list, but how to delete a property with in an element?
I think you need used : #JsonIgnore in Id look like:
#JsonIgnore
Field you want remove in reponse.
Or you can create DTO and put all field you want return look like :
public class PersonDTO {
//all field you want return
}
You can of course set id null or add ignores in serialization but maybe you do not want to load id at all. Usually you then would use DTO or Tuple to decide what fields to populate. So not first to populate all and then remove unneeded (I have not used your Person but just one simplified example class).
Tuple query in your repository would simply be like (JPQL):
#Query("SELECT te.name AS name, te.created as created FROM TestEntity te")
List<Tuple> findAllTuple();
This would need then do extra work to have tuple to correspond original entity when serialized. So preferably with a DTO, like:
// This class would be exactly as your Person but without that id
#AllArgsConstructor // you need the constructor for new in jpql
public class TestEntityDto {
private String name;
private LocalDateTime created;
}
while the query in your repository would be like:
#Query("SELECT NEW org.example.data.entity.dto.TestEntityDto(te.name, te.created) FROM TestEntity te")
List<TestEntityDto> findAllDto();

Inject data in json entity with Spring Data REST

I have JPA entity for department:
public class Department {
#Id
#Column(unique = true, nullable = false)
private long id;
#Basic
#Column
#Nationalized
private String name;
#Basic
#Column(length = 400)
#Nationalized
private String branch;
...
}
And REST repository
#RepositoryRestResource(collectionResourceRel = "departments", path = "departments")
public interface DepartmentRestRepository extends PagingAndSortingRepository<Department, Long> {
...
}
Entity's branch field is IDs of entity parent departments separated by space, e.g. 1 2 3.
When I query specific department via /api/departments/ID is it possible to attach to it field like parents with all parent entities queried?
I tryed to add getParents method to entity, but it obviously gave me unneeded parents queries with all entities recursively.
Update 2019.01.17:
As a workaround I splitted Department entity into Department and DepartmentWithParents. I added Department getParents() method to DepartmentWithParents entity and exposed REST API method that returns DepartmentWithParents.
Is there better way?
As a workaround I splitted Department entity into Department and DepartmentWithParents. I added Department getParents() method to DepartmentWithParents entity and exposed REST API method that returns DepartmentWithParents.

Spring-Mongo : mapping mongo document field/s to BasicDBObject/Map of BasicDBObject of an Entity

I have an entity ProjectCycle mapped to mongo DB collection ProjectCycle. I am trying to retrieve 2 fields, _id and Status. I am able to retrieve both like the following
#Document(collection="ProjectCycle")
public class ProjectCycle {
#Id
private String id;
#Field("Status")
private String status;
//getters and setters
}
Application.java
Query query = new Query();
query.fields().include("Status");
Criteria criteria = new Criteria();
criteria.and("_id").is("1000");
query.addCriteria(criteria);
Iterable<ProjectCycle> objectList = mongoOperations.find(query, ProjectCycle.class);
for(ProjectCycle obj : objectList) {
System.out.println("_id "+obj.getId());
System.out.println("status "+obj.getStatus());
}
Output
_id 1000
status Approved
But, the problem is when i use an Entity with field private DBObject basicDbObject; instead of private String status; i am getting value as null instead of Approved
I have tried like the following
public class ProjectCycle {
#Id
private String id;
private DBObject basicDbObject;
//getter & setter
}
What I am trying to achieve is that, the collection 'ProjectCycle' is very large and creating a POJO corresponding to it is quiet difficult. Also I am only reading data from mongoDB. So creating the entire POJO is time wasting and tedious.
How I can achieve mapping between any field/fields from mongo Collection to entity?.
Will it be possible to create a Map<String, BasicDBObject> objectMap; to fields returned from query? I am using Spring-data-mongodb for the same.
Version details
Spring 4.0.7.RELEASE
spring-data-mongodb 1.7.2.RELEASE
Try mapping your query like below.
Iterable<BasicDBObject> objectList = mongoOperations.find(query, BasicDBObject.class, collectionname);
for(BasicDBObject obj : objectList) {
System.out.println("_id "+obj.get("id"));
System.out.println("status "+obj.get("status"));
}

Resources