Spring Data Cassandra Query DSL RxJava2 - java

So I am using Spring Data Cassandra and RxJava, I am looking for a way to use RxJava Observable with custom query building (the find..by abstraction is to complicated to use in my case) and I was planning on using QueryDSL (the method findAll(Predicate), but it does not enable Async :/)
So far my best shot is to use AsyncCassandraTemplate to build a Query and return it as ListenableFuture so that it can be mapped to a Observable and be used with RxJava's Observable. Is there any other way?

There's no QueryDsl support Spring Data for Apache Cassandra. You can use Query objects to create queries and ReactiveCassandraTemplate for reactive API usage:
Mono<Person> person = cassandraTemplate.selectOneById(query(where("age").is(33)), Person.class);
Maybe<Person> maybe = Flowable.fromPublisher(person).firstElement();

Related

Is there a way to dynamically generate Spring Data Jpa queries?

I'm writing an app using Spring Boot, Spring Data. And I'm trying to implement a filtering feature based on different filter parameters.
Using Spring Data queries we can define quite complex logic, e.g.:
#Query("SELECT u FROM User u WHERE u.status = 1")
Collection<User> findAllActiveUsers();
But what if the number of where clauses, order, limit, number of different parameters are unknown till we make an actual filter request which can be quite complex.
Right now filter params are send in a json object which I parse and retrieve them and the result sql query can be something like this:
SELECT * FROM table
WHERE field1 != `value1` and (field1 != ` value2 `OR (field1 = `value3` AND filed2 < 3))
AND field2 != 99
Is it possible to generate dynamically complex queries with undefined (till the actual filter request, during runtime) number of params, where clauses and other stuff?
I use this active project RSQL for JPA
https://github.com/perplexhub/rsql-jpa-specification
Sometime back I wrote an article on Spring Data JPA Query with Dynamic Where Clause. In this example you can send a Where Clause and Map of parameters for that. You can make use of this and modify it a bit suit your needs.
I would suggest using Spring JPA Specification
ref : https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/
To build it in a type safe manner, you can use FluentJPA.

How to make dynamic queries at run-time in Spring Boot and Data?

I am new to Java and started with Spring Boot and Spring Data JPA, so I know 2 ways on how to fetch data:
by Repository layer, with Literal method naming: FindOneByCity(String city);
by custom repo, with #Query annotation: #Query('select * from table where city like ?');
Both ways are statical designed.
How should I do to get data of a query that I have to build at run time?
What I am trying to achieve is the possibility to create dynamic reports without touching the code. A table would have records of reports with names and SQl queries with default parameters like begin_date, end_date etc, but with a variety of bodies. Example:
"Sales report by payment method" | select * from sales where met_pay = %pay_method% and date is between %begin_date% and %end_date%;
The Criteria API is mainly designed for that.
It provides an alternative way to define JPA queries.
With it you could build dynamic queries according to data provided at runtime.
To use it, you will need to create a custom repository implementation ant not only an interface.
You will indeed need to inject an EntityManager to create needed objects to create and execute the CriteriaQuery.
You will of course have to write boiler plate code to build the query and execute it.
This section explains how to create a custom repository with Spring Boot.
About your edit :
What I am trying to achieve is the possibility to create dynamic
reports without touching the code. A table would have records of
reports with names and SQl queries with default parameters like
begin_date, end_date etc, but with a variety of bodies.
If the queries are written at the hand in a plain text file, Criteria will not be the best choice as JPQL/SQL query and Criteria query are really not written in the same way.
In the Java code, mapping the JPQL/SQL queries defined in a plain text file to a Map<String, String> structure would be more adapted.
But I have some doubts on the feasibility of what you want to do.
Queries may have specific parameters, for some cases, you would not other choice than modifying the code. Specificities in parameters will do query maintainability very hard and error prone. Personally, I would implement the need by allowing the client to select for each field if a condition should be applied.
Then from the implementation side, I would use this user information to build my CriteriaQuery.
And there Criteria will do an excellent job : less code duplication, more adaptability for the query building and in addition more type-checks at compile type.
Spring-data repositories use EntityManager beneath. Repository classes are just another layer for the user not to worry about the details. But if a user wants to get his hands dirty, then of course spring wouldn't mind.
That is when you can use EntityManager directly.
Let us assume you have a Repository Class like AbcRepository
interface AbcRepository extends JpaRepository<Abc, String> {
}
You can create a custom repository like
interface CustomizedAbcRepository {
void someCustomMethod(User user);
}
The implementation class looks like
class CustomizedAbcRepositoryImpl implements CustomizedAbcRepository {
#Autowired
EntityManager entityManager;
public void someCustomMethod(User user) {
// You can build your custom query using Criteria or Criteria Builder
// and then use that in entityManager methods
}
}
Just a word of caution, the naming of the Customized interface and Customized implementating class is very important
In last versions of Spring Data was added ability to use JPA Criteria API. For more information see blog post https://jverhoelen.github.io/spring-data-queries-jpa-criteria-api/ .

Spring data redis repository doesn't support collection query?

We can do 'findByXXsIn' in spring data JPA, but it seems that I failed to do this in spring data Redis, is there an alternative to do this?
I tagged an object, and store the relation in Redis(tagId,targetId,targetType).
public interface TagRelationRepository {
Page<TagRelation> findTagRelationByTagIdIn(List<String> tagIds,Pageable page);
Page<TagRelation> findTagRelationByTargetType(TagTargetType targetType,Pageable page);
List<TagRelation> findByTargetIdInAndTargetType(List<Long> targetIds,TagTargetType targetType);
}
It's many to many relationship, I want to get the relations by tagIds but just failed.
Currently only simple finder methods with the keywords Is or Equals as well as combinations of those using And / Or are supported.
Please refer to Table 5. Supported keywords in the reference manual for Queries and Query Methods.

Equivalent of IQueryable in Spring Data

I'm used to .Net and LINQtoEntities, especially the IQueryable part which allows to carry a request through different functions before fetching the results.
Does anything like this exist in spring data ? Or any other java ORM ?
Basic example of what I'd like to be able to do :
private IQueryable<Todo> GetAll(){
context.Todos.Where(t => !t.Deleted);
}
public IEnumerable<Todo> GetDoneTodos(){
GetAll().Where(t => t.Done).ToList();
}
You can use Spring Data's QueryDSL integration. Basically, you extend the QueryDslPredicateExecutor in your repository interface and it add a findAll method that gets a QueryDSL Predicate and filter all the results based on that Predicate. Suppose we have domain object, say Greeting, then we'd have repository like this:
public interface GreetingRepository extends QueryDslPredicateExecutor<Greeting> {}
Then you can use generated QModels generated by QueryDSL to create a Predicate and pass it to our greetingRepository. Suppose we're going to filter all the Greetings by one specific user:
Predicate filterByUser = greeting.user.eq(someUser);
greetingRepository.findAll(filterByUser);
greeting is a metamodel generated by QueryDSL based on our Greeting model.
Note 1: You can see how you can integrate Spring Data and QueryDSL here and see more examples for QueryDSL's Predicates here.
Note 2: QueryDslPredicateExecutor also provides findOne(Predicate predicate), count(Predicate predicate) and exists(Predicate predicate) methods which are useful and self-explanatory, of course.
Note 3: You can achieve almost the same thing with Specifications but in my opnion QueryDSL has more elegant and readable Predicates.

Generating a Hibernate Criteria query from parameters

I have to create a query in our backend application using the parameters obtained from the client. Consider this diagram:
I have entities (Type field), those entities' fields (Parameter), a relation, a value and an operand. So in sql terms the table above translates to this:
... WHERE Item.reach_complience = ”<1%”
and Item.technical.type = ”RES”
and Item.technical.value <= ”1k”
and Item.technical.value >= ”4K7”
and (Item.technical.footprint = ”RC0603” or Item.technical.footprint = ”RC0805”)
and Item.classification.incurrent_handling = ”prefered-to-use”
I really don't want to reinvent the weel here, so my question is:
Is there a Criteria factory libarary which uses JPA or more specifically Hibernate or is there some 3rd party library which can be used to create criteria queries? We are using Eclipse RCP on the frontend and data arrives to the backend (Spring) through an Apache Cxf service. I wish to write maintainable using JPA's query syntax.
Yes. I think ISearch is the best: http://code.google.com/p/hibernate-generic-dao/wiki/Search

Categories