Spring jdbcTemplate -add filter to query - spring

I write a queries in jdbcTemplate to create reports, Now I want to add filter to the reports. for example if i have query to create report of all contacts per day, now I want to filter it that be just between two dates not all
What the best way to do it ?
There is a special way to do it in Spring jdbcTemplate?

See following tutorial and example code taken from that one below.
public Person select(String name){
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("name", name);
String selectAllSql = "SELECT * FROM PERSON where name = :name";
List<Person> persons = getJdbcTemplate().query(selectAllSql, new PersonRowMapper(),parameters);
return persons.get(0);
}
}
To answer your comment:
If some times i dont use the filter what i do with the parmeters what i have to send
You have two options
1) You will need to use if statements to construct your sql and parameters.
2) Use another library for this purpose. I used ElSql in production before.

Related

Get a list of entities by a list of attributes in Spring Boot eg. findAllByIdIn(List<Integer> ids)

I need help getting a list of entities by a list of attributes, say "id', "name' etc. Below is what I have so far and I'm expecting three entities but the result shows only one. The logic of the code below is basically to grab all entries with LOGIN as eventType and customer Id in the event repo. We're then getting the "eventdetailsIds" into a separate collection from the result found and searching(findByIdIn) for them in the LoginEventRepo. EventDetailsId is more or less a foreign key that joins event repo and loginEvent Repo. PS. I have implemented manually but I just need a more concise approach. Thanks.
public List<CustomerEventResponse> getAllCustomerLogins(String customerId) {
List<CustomerEventResponse> customerEventResponses;
List<EventEntity> eventEntityList = eventRepository.findByCustomerIdAndEventType(customerId, LOGIN_EVENT);
List<LoginEventDetailsEntity> loginEventDetailsEntityList = new ArrayList<>();
List<Integer> eventDetailsIds = new ArrayList<>();
for(EventEntity e: eventEntityList){
eventDetailsIds.add(e.getEventDetailsId());
Optional<LoginEventDetailsEntity> loginEventDetails = loginEventDetailsRepository.findById(e.getEventDetailsId());
loginEventDetails.ifPresent(loginEventDetailsEntityList::add);
}
List<LoginEventDetailsEntity> loginDetails = loginEventDetailsRepository.findAllById(eventDetailsIds);
The database is below:
Thanks.

Spring Data elastic search with out entity fields

I'm using spring data elastic search, Now my document do not have any static fields, and it is accumulated data per qtr, I will be getting ~6GB/qtr (we call them as versions). Lets say we get 5GB of data in Jan 2021 with 140 columns, in the next version I may get 130 / 120 columns, which we do not know, The end user requirement is to get the information from the database and show it in a tabular format, and he can filter the data. In MongoDB we have BasicDBObject, do we have anything in springboot elasticsearch
I can provide, let say 4-5 columns which are common in every version record and apart from that, I need to retrieve the data without mentioning the column names in the pojo, and I need to use filters on them just like I can do in MongoDB
List<BaseClass> getMultiSearch(#RequestBody Map<String, Object>[] attributes) {
Query orQuery = new Query();
Criteria orCriteria = new Criteria();
List<Criteria> orExpression = new ArrayList<>();
for (Map<String, Object> accounts : attributes) {
Criteria expression = new Criteria();
accounts.forEach((key, value) -> expression.and(key).is(value));
orExpression.add(expression);
}
orQuery.addCriteria(orCriteria.orOperator(orExpression.toArray(new Criteria[orExpression.size()])));
return mongoOperations.find(orQuery, BaseClass.class);
}
You can define an entity class for example like this:
public class GenericEntity extends LinkedHashMap<String, Object> {
}
To have that returned in your calling site:
public SearchHits<GenericEntity> allGeneric() {
var criteria = Criteria.where("fieldname").is("value");
Query query = new CriteriaQuery(criteria);
return operations.search(query, GenericEntity.class, IndexCoordinates.of("indexname"));
}
But notice: when writing data into Elasticsearch, the mapping for new fields/properties in that index will be dynamically updated. And there is a limit as to how man entries a mapping can have (https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-settings-limit.html). So take care not to run into that limit.

how to convert HAC flexible query to DAO query

I'm using below flexible query in HMC and it's working fine.
The same query needs to convert the DAO layer and input is a data parameter.
Please any help on this?
SELECT * FROM {Product} WHERE {creationtime} >= TO_DATE('2020/02/19','YYYY/MM/DD')
The complete and definitive guide for the creation of Flexiqueries and corresponding DAO code.
Refer DefaultProductDao and create one for your requirement or you can extend it if you want to reuse any function. I hope by looking at the class, you'll have an understanding of how to write and execute the flexi query in the SAP Hybris.
Converting your query to DAO
Here, I would suggest avoiding using TO_DATE or any DB function to ensure that the query is not DB dependent. In your case, you can parse string date to Java Date object and pass it to the query something like below
String query = "SELECT * FROM {"+ ProductModel._TYPECODE +"} WHERE {"+ ProductModel.CREATIONTIME +"} >= ?"+ProductModel.CREATIONTIME;
final FlexibleSearchQuery searchQuery = new FlexibleSearchQuery(query);
final Map<String, Object> params = new HashMap<String, Object>();
params.put(ProductModel.CREATIONTIME, getDateObject("2020/02/19"));
searchQuery.addQueryParameters(params);
final SearchResult searchResult = getFlexibleSearchService().search(searchQuery);
return searchResult.getResult();
Method
private Date getDateObject(String date)
{
// logic to parse your string date (YYYY/MM/DD) to java Date object
return new Date(); //return your parsed date object here
}

Sorting a custom JPA query with pageable

So, I've already done this using the standard Spring Data JPA interface which extends PagingAndSortingRepository in order to achieve pagination and sorting for a REST API. The thing is, now I want to achieve the very same thing but now using just vanilla JPA and so far so good I managed to get my API to paginate but the sorting doesn't work at all. Every time I try to set the parameter (from a pageable object using pageable.getSort()) it ends with a query error (either if I just send a string as parameter like "name" or just send the sort object, it shows errors).
Here's some code:
My repo implementation:
#Override
public List<Project> findByAll(Pageable pageable) {
Query query = em.createQuery("SELECT project FROM Project project ORDER BY :sort");
query.setParameter("sort", pageable.getSort());
query.setMaxResults(pageable.getPageSize());
query.setFirstResult(pageable.getPageSize() * pageable.getPageNumber());
return query.getResultList();
}
My service:
#Override
public Page<Project> findAll(Pageable pageable) {
objects = Lists.newArrayList(repository.findByAll(pageable));
PageImpl<Project> pages= new PageImpl<Project>(objects, pageable, repository.count());
return pages;
}
To be clear, I'm filling the Pageable object via URI and from the console I can say it's actually getting the data, so I assume the problem is with the repo.
Edit: This is the error I get when I replace the setParameter("sort", ...) for a hardcoded string aka query.setParameter("sort", "name"):
java.lang.NumberFormatException: For input string: "name"
And I think this method should stand for strings as well. If I use query.setParameter("sort", pageable.getSort()), the error is the same.
The order by cannot be set as a query parameter. Also, the Pageable.getSort().toString() likely won't return a string suitable for use in an order by clause as it will result in a String that represents the Order as property: ORDER, note the colon.
Here are some modifications that will work, assuming Java 8...
String order = StringUtils.collectionToCommaDelimitedString(
StreamSupport.stream(sort.spliterator(), false)
.map(o -> o.getProperty() + " " + o.getDirection())
.collect(Collectors.toList()));
Query query = em.createQuery(
String.format("SELECT project FROM Project project ORDER BY %s", order));

Using spring jdbc template to query for list of parameters

New to Spring JDBC template but I'm wondering if I am able to pass a list of parameters and execute query once for each parameter in list. As I've seen many examples, the list of parameters being passed is for the execution of the query using all the parameters provided. Rather I am trying to execute query multiple times and for each time using new parameter in list.
For example:
Let's say I have a List of Ids - params (Strings)
List<String> params = new ArrayList<String>();
params.add("1234");
params.add("2345");
trying to do something like:
getJdbcTemplate().query(sql, params, new CustomResultSetExtractor());
which I know as per documentation is not allowed. I mean for one it has to be an array. I've seen simple examples where query is something like "select * from employee where id = ?" and they are passing new Object[]{"1234"} into method. And I'm trying to avoid the IN() condition. In my case each id will return multiple rows which is why I'm using ResultSetExtractor.
I know one option would be to iterate over list and include each id in list as a parameter, something like:
for(String id : params){
getJdbcTemplate().query(sql, new Object[]{id}, new CustomResultSetExtractor());
}
Just want to know if I can do this some other way. Sorry, I Should mention that I am trying to do a Select. Originally was hoping to return a List of custom objects for each resultset.
You do need to pass an array of params for the API, but you may also assume that your first param is an array. I believe this should work:
String sql = "select * from employee where id in (:ids)"; // or should there be '?'
getJdbcTemplate().query(sql, new Object[]{params}, new CustomResultSetExtractor());
Or you could explicitly specify, that the parameter is an array
getJdbcTemplate().query(sql, new Object[]{params}, new int[]{java.sql.Types.ARRAY}, new CustomResultSetExtractor());
You can use preparedStatement and do batch job:
eg. from http://docs.spring.io/spring/docs/current/spring-framework-reference/html/jdbc.html
public int[] batchUpdate(final List<Actor> actors) {
int[] updateCounts = jdbcTemplate.batchUpdate("update t_actor set first_name = ?, " +
"last_name = ? where id = ?",
new BatchPreparedStatementSetter() {
public void setValues(PreparedStatement ps, int i) throws SQLException {
ps.setString(1, actors.get(i).getFirstName());
ps.setString(2, actors.get(i).getLastName());
ps.setLong(3, actors.get(i).getId().longValue());
}
public int getBatchSize() {
return actors.size();
}
});
return updateCounts;
}
I know you don't want to use the in clause, but I think its the best solution for your problem.
If you use a for in this way, I think it's not optimal.
for(String id : params){
getJdbcTemplate().query(sql, new Object[]{id}, new CustomResultSetExtractor());
}
I think it's a better solution to use the in clause. And then use a ResultSetExtractor to iterate over the result data. Your extractor can return a Map instead of a List, actually a Map of List.
Map<Integer, List<MyObject>>
Here there is a simple tutorial explaining its use
http://pure-essence.net/2011/03/16/how-to-execute-in-sql-in-spring-jdbctemplate/
I think this is the best solution:
public List<TestUser> findUserByIds(int[] ids) {
String[] s = new String[ids.length];
Arrays.fill(s, "?");
String sql = StringUtils.join(s, ',');
return jdbcTemplate.query(String.format("select * from users where id in (%s)", sql),
ArrayUtils.toObject(ids), new BeanPropertyRowMapper<>(TestUser.class));
}
this one maybe what you want. BeanPropertyRowMapper is just for example, it will be very slow when there's a lot of records. you should change it to another more efficient RowMapper.

Resources