Spring Data JPA Determine Overlapping date range - spring-data-jpa

I am new to Spring Data Jpa
I have the below objects
public class VehicleDetail {
private long vehicleDetailId;
#OneToMany(mappedBy = "vehicleDetail")
private List<NonAvailabilityStatus> nonAvailabilityStatus = new ArrayList<NonAvailabilityStatus>();
}
public class NonAvailabilityStatus{
private long nonAvailabilityStatusId;
#Column(name="START_DT_TM")
private Date nonAvailabiltyStartDateTime;
#Column(name="END_DT_TM")
private Date nonAvailabiltyEndDateTime;
}
I want to check if the current date and current date+1 overlaps between nonAvailabiltyStartDateTime and nonAvailabiltyEndDateTime using method name query. I tried findByNonAvailabilityStatusNonAvailabiltyStartDateTimeIsBeforeAndNonAvailabilityStatusNonAvailabiltyEndDateTimeAfter(Date startDate, Date endDate), and it did not work.

Related

How to write criteria Query with multiple Or condition for a subdocument in mongoDB

I am trying to write a criteria query for document which contains subdocument in it. And I want to query on both the items of the document and the subdocuments with some and as well as multiple or conditions. Below is my document strucutre
public class ParentEntity {
#Id
private String id;
private String sName;
private String itemDesc;
private String localTimeStamp;
private boolean isStatus;
private List<ChildEntity> childEntity;
private List<String> itemList;
}
public class ChildEntity{
private String prc;
private LocalDate effDate;
}
Now I want to query on a condition which will satisfy the below condition
We will fetch if isStatus is true
We will fetch if effDate is today.
We will fetch if localTimeStamp= null or localTimeStamp is empty or localTimeStamp field does not exists in mongoDb collection
so in one expression the condition is 1 and (2 or 3)
Below is my code what i have done
Criteria criteria = new Criteria();
Query query = new Query();
criteria.add("isStatus").is(true);
criteria.andOperator(criteria.orOperator(Criteria.where("childentity.effDate").is(LocalDate.now),Criteria.where("localTimeStamp").is("");
query.addCriteria(criteria);
List<ParentEntity> list = mongoTemplate.find(query,ParentEntity.class);
This is giving me result while the isStatus is true and effDate is today and localTimeStamp is "" , but i want to check also the localTimeStamp=null and localTimeStamp filed does not exists in the document.
How I will include 3 or s in a single condition with one and operator ?
Someone help me , i am new in mongoDb.
I suggest investigating spring-boot-starter-data-search.
add the starter to your pom file:
<dependency>
<groupId>app.commerce-io</groupId>
<artifactId>spring-boot-starter-data-search-mongodb</artifactId>
<version>1.1.0</version>
</dependency>
enable the Search Repository:
#Configuration
#EnableMongoRepositories(repositoryBaseClass = SearchRepositoryImpl.class)
public class MyConfiguration {
}
make your repository extends SearchRepository
#Repository
public interface UserRepository extends SearchRepository<UserDocument, String> {
}
use this repository to get your data
String search = "address.name: myName or email: myEmail and (address.country: FR and address.city: Paris)";
Page<UserDocument> result = userRepository.findAll(search, pageable);
You can find a demo for MongoDB here
Disclaimer: I'm a contributor of spring-boot-starter-data-search

How to get last record in spring mongo?

I have a transaction class which stores the each transaction of a customer,Following are the fields in this class.
class Transaction{
#Id
private String id;
private Date date;
private String customerId;
private double openBalance;
private double transctionAmount;
private double finalAmount;
}
I need to fetch only the last inserted record of a customer (let say for customerId = cust123).
I defined following function in repository.
public interface TranscationRepository extends MongoRepository<Transaction, String> {
Optional<Transaction> findTopByCustomerIdOrderByIdDesc(String id);
}
This method giving last entry not by customerId but overall. I tried few modifications to it but did not get success.
I know I can findAllByCustomer but I don't want to pull huge list of transaction which is of no use in this use case. What is correct signature in spring mongo to get last inserted record by a field? I am ok to use custom #Query also.
Thank you.

How can I get data from #DBRef document using #Query -> Spring data mongo

I need help to get the data from another document I have the following class.
#Data
#Document(collection = "tmVersion")
public class TmVersion {
#Id
private String id;
private String cVrVersionId;
#DBRef
private TaApplicationVersion taApplicationVersion;
}
and
#Data
#Document(collection = "taApplicationVersion")
public class TaApplicationVersion {
#Id
private String id;
private String dVrAppName;
private String dVrAppCode;
}
This is my repository in which I map what I want to be shown but in taApplicationVersion I need to show all this object also how is it done?
#Query(value="{}", fields="{'cVrVersionId': 1, 'taApplicationVersion.dVrAppName': 2,
'dVrVersionNumber': 3}")
Page<TmVersion> getAllVersionWithOutFile(Pageable pageable)
Couple of things to mention here.
If you want this kind of join between tables, then you need to rethink your choice of Mongodb as database. No Sql Databases thrive on the fact that there is very less coupling between tables(collections). So if you are using #DBRef, it negates that. Mongodb themselves do not recommend using #DBRef.
This cannot be achieved with the method like you have in the repository. You need to use Projections. Here is the documentation for that.
Create a Porjection interface like this. Here you can control which fields you need to include in the Main class(TmVersion)
#ProjectedPayload
public interface TmVersionProjection {
#Value("#{#taApplicationVersionRepository.findById(target.taApplicationVersion.id)}")
public TaApplicationVersion getTaApplicationVersion();
public String getId();
public String getcVrVersionId();
}
Change the TmVersionRepository like this
public interface TmVersionRepository extends MongoRepository<TmVersion, String> {
#Query(value="{}")
Page<TmVersionProjection> getAllVersionWithOutFile(Pageable pageable);
}
Create a new Repository for TaApplicationVersion. You can add #Query on top of this method and control which fields from subclass needs to be returned.
public interface TaApplicationVersionRepository extends MongoRepository<TaApplicationVersion, String> {
TaApplicationVersion findById(String id);
}

Spring Data update mongodb Document with DBRF lazy attribute

I want to update a MongoDB document containing a dbrf lazy attribute using spring data.
First of all, I load the existing document, I change the attributes I want and after that, I call #Repository save method, but when I check the document in MongoDB the dbrf lazy attribute is null.
I tried to load the attribute before by calling getAttribute, but that doesn't fix the problem.
Someone could help me?
Thanks
I have the Collection below:
#Data
#Document(collection = "calendriers")
public class CalendrierEntity {
#Id
#AutoGenerate(SequanceKey.CALENDRIER)
private Long id;
#NotNul
private String label;
#NotNull
private HorairesEntity horairesEntity;
#DBRef(lazy = true)
#CascadeSave
#Getter(AccessLevel.NONE)
private List<AbsenceEntity> absenceEntities;
}
and the repository bellow :
#Repository
public interface AbsenceRepository extends MongoRepository<CalendrierEntity, Long> {
AbsenceEntity findById(Long enfantId, LocalDate localDate);
}
I have calendrier document with Id 1L and want to update his label.
The calendrier document have allready a list of Absences.
this my code to update the label.
#Transactional
public void updateLabelCalendrier(Long id, String label){
CalendrierEntity calendrier = calenderRepository.findById(1L);
calendrier.setLabel(label);
calenderRepository.save(calendrier);
}
but when i check data in mongodb, i have the new label but my list of absences became null.

How can I get a list of a single field value from an entity?

I am working on a Jhipster app Java service and Angular 5 UI. I have an entity working fine, but I need to get a list of one of the fields (customer) from that entity to display in the UI.
In this case it's a single table I am using which contains the client name, so I am trying to get a distinct list returned for read only.
I have tried creating a custom repository and added a function into the service, Impl class and resource class.
Upon startup its failing with cannot find a property getClientNameList on the entity.
I have show a snippet of the code from the Entity class, the custom repository and the method I added into the PostsServiceImpl class.
Can someone please steer me in the right direction?
Thanks.
// Entity Class //
#Entity
#Table(name = "posts")
public class Posts implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name="client_name")
private String clientName;
// Other fields here
...
}
// Custom Repository //
#Repository
public interface JobsRepositoryCustom {
List<String> getClientNameList();
}
// PostsServiceImpl //
public class PostsServiceImpl implements PostsService {
EntityManager entityManager;
public List<String> getClientNameList() {
Query query = entityManager.createNativeQuery("SELECT clientName FROM Posts", Posts.class);
return query.getResultList();
}
}
Your error might be more specifically that clientName is not found. It is not found because if you run a native query you need to use the database column names.
So change:
"SELECT clientName FROM Posts"
to
"SELECT client_name FROM Posts"