Spring JDBC- Rowmapping a ready result set - spring

In my project, i am giving two in value and i get two out resultset from my procedure.
After getting them, i have to rowmap the each resultset.
I tried to do this with my rowmapper class, but i am not sure. How it works mapRow method of RowMapper?
Thanks!
List<Pax> paxList=new ArrayList<>();
int paxIndex=1;
while(tc.getCursor(4).next()) {
paxList.add(paxRowMapper.mapRow(tc.getCursor(4),paxIndex));
paxIndex++;
}

Related

Spring-AOP Return value of Aspect #AfterReturn is not working

#AfterReturning(value = "anyPublicMethod() && applyPrivacy()", returning = "result")
public Object afterReturning(JoinPoint joinPoint, Object result) {
return someService.createNewObjectWithHelpOfResult(result);
}
My intention was to fill some null values in result fields. So in method createNewObjectWithHelpOfResult I'm creating a new Object and setting only the required values. But return value is not reflecting after afterReturning method is finished. But if I do mutations on result. They're very well reflected after aspect #AfterReturning method ends, but I want the return value to be used? Is this not possible? I'll have to do mutation only?
What #M.Deinum explained, is documented in the Spring manual, section "After Returning Advice". The end of the section reads:
Please note that it is not possible to return a totally different reference when using after returning advice.
Therefore, you cannot just make your #AfterReturning advice have a return type other than void and hope it will magically return something. As the advice type name implies, all 3 types of #After* advices run after the method has returned already. There is nothing you can do to change the result (except for altering internal state of an object instance). You can merely read (and e.g. log) it.
The solution, like #M.Deinum said, is an #Around advice, see also again the Spring manual.
It is generally a good idea to at least study the manual and learn some basics or take a look at examples before asking questions in public. I am sure you did not find any valid example for an #After* advice with non-void return type.
I am using #AfterReturning on the methods whose return type is String but instead of String I am getting null as result
#AfterReturning(value = "execution(* com.example.demo.aop.business..(..))", returning = "result")
public void afterA(JoinPoint joinPoint, Object result) {
log.info("After method {} returned with value {}", joinPoint, result);
}
O/P - After method execution(void com.example.demo.aop.business.Business2.disp()) returned with value null

spring data redis cluster pipeline support

Is there a plan to support "pipelined" operations for the spring data redis library when connecting to redis clustered version. There is considerable performance differences between pipelined & non-pipelined operations. If there is no such plan what are other viable options?
Spring Data Redis provides several RedisTemplate methods for executing commands in a pipeline. If you don’t care about the results of the pipelined operations, you can use the standard execute method, passing true for the pipeline argument. The executePipelined methods will execute the provided RedisCallback or SessionCallback in a pipeline and return the results. For example:
//pop a specified number of items from a queue
List<Object> results = stringRedisTemplate.executePipelined(
new RedisCallback<Object>() {
public Object doInRedis(RedisConnection connection) throws DataAccessException {
StringRedisConnection stringRedisConn = (StringRedisConnection)connection;
for(int i=0; i< batchSize; i++) {
stringRedisConn.rPop("myqueue");
}
return null;
}
});
The example above executes a bulk right pop of items from a queue in a pipeline. The results List contains all of the popped items. RedisTemplate uses its value, hash key, and hash value serializers to deserialize all results before returning, so the returned items in the above example will be Strings. There are additional executePipelined methods that allow you to pass a custom serializer for pipelined results.
Note that the value returned from the RedisCallback is required to be null, as this value is discarded in favor of returning the results of the pipelined commands.
Reference: http://docs.spring.io/spring-data/redis/docs/current/reference/html/#pipeline
Spring data redis does not supports the pipeline on cluster. So We can do it by our self in our application. If you use spring-data-redis and Jedis library.
So for that, we have to take Jedis Connection indirectly from Jedis Pool. Now if you only know keys of cluster then for that first you need to find out slot associated to key. You can get it by following way.
int slot = JedisClusterCRC16.getSlot(hKey);
Second, you can get JedisCluster connection by following way
JedisClusterConnection jedisClusterConnection = (JedisClusterConnection)stringRedisTemplate.getConnectionFactory().getClusterConnection();
JedisCluster jedisCluster = jedisClusterConnection.getNativeConnection();
Now you have JedisCluster connection but it is not enough to get Jedis connection from Jedis pool. Because JedisCluster not exposing connection handler directly and JedisSlotConnectionHandler classing having method which returns the jedis connection from slot. so for that we have to copy the BinaryJedisCluster class from package redis.clients.jedis into our application with same class and package name and you have to add following method to expose connection handler.
public JedisSlotBasedConnectionHandler getConnectionHandler() {
return (JedisSlotBasedConnectionHandler) this.connectionHandler;
}
Finally, you can able to get Jedis Connection by calling getJedisConnectionFromSlot(slot) method
JedisSlotBasedConnectionHandler jedisClusterConnectionHandler = jedisCluster.getConnectionHandler();
Jedis connection = jedisClusterConnectionHandler.getConnectionFromSlot(slot);
Pipeline pipeline = connection.pipelined();
pipeline.somecommand....
pipeline.sync();
Reference link

Lazy Hibernate Initialization No Session, Could not initialize Proxy

I am creating a e-prescribing module will allow several orders to be created and added to a list before being confirmed (saved in DB at once together). I have two forms - One where the order is created and the second with a link to add more orders, where the submit button will store all the orders (ArrayList items) in the DB. i.e. Each order upon creation gets added to an ArrayList [createNewDrugOrder() method below]
When I try to save each order inside this method - it works fine. but my requirement is to have the facility to store the orders as a draft before confirming them (storing in DB).
public class DrugordersPageController{
SessionFactory sessionfactory;
public void controller(){
if ("addDraftOrder".equals(action)){
createNewDrugOrder();
}
if ("confirmOrder".equals(action)){
saveOrder();
}
}
createNewDrugOrder(){
DrugOrder order = new DrugOrder();
order.setDose(1);
order.setDuration(1);
order.setQuantity(1);
ConfirmOrderClass.orderToConfirm.add(order);
}
saveOrder(){
DrugOrder order = ConfirmOrderClass.getDrugOrderMain();
order = (DrugOrder) Context.getOrderService().saveOrder(order, null); //Here is where error is thrown
}
}
class ConfirmOrderClass{
public static ArrayList<DrugOrder> orderToConfirm = new ArrayList<DrugOrder>();
public static ArrayList<DrugOrder> getDrugOrderMain(){
return orderToConfirm;
}
}
I understand this is a case of object being detached from the session, but I am unable to get it fixed. Calling session.save or session.update in the second form doesn't help..Neither does Hibernate.initialize(object) or adding a #Transactional notation
when I call Session s = sessionfactory.getCurrentSession or openSession, i still get null pointer error. Although I am able to retrieve the values of order.getDose(), order.getDuration() etc..
Please help!

Is paging broken with spring data solr when using group fields?

I currently use the spring data solr library and implement its repository interfaces, I'm trying to add functionality to one of my custom queries that uses a Solr template with a SimpleQuery. it currently uses paging which appears to be working well, however, I want to use a Group field so sibling products are only counted once, at their first occurrence. I have set the group field on the query and it works well, however, it still seems to be using the un-grouped number of documents when constructing the page attributes.
is there a known work around for this?
the query syntax provides the following parameter for this purpose, but it would seem that Spring Data Solr isn’t taking advantage of it. &group.ngroups=true should return the number of groups in the result and thus give a correct page numbering.
any other info would be appreciated.
There are actually two ways to add this parameter.
Queries are converted to the solr format using QueryParsers, so it would be possible to register a modified one.
QueryParser modifiedParser = new DefaultQueryParser() {
#Override
protected void appendGroupByFields(SolrQuery solrQuery, List<Field> fields) {
super.appendGroupByFields(solrQuery, fields);
solrQuery.set(GroupParams.GROUP_TOTAL_COUNT, true);
}
};
solrTemplate.registerQueryParser(Query.class, modifiedParser);
Using a SolrCallback would be a less intrusive option:
final Query query = //...whatever query you have.
List<DomainType> result = solrTemplate.execute(new SolrCallback<List<DomainType>>() {
#Override
public List<DomainType> doInSolr(SolrServer solrServer) throws SolrServerException, IOException {
SolrQuery solrQuery = new QueryParsers().getForClass(query.getClass()).constructSolrQuery(query);
//add missing params
solrQuery.set(GroupParams.GROUP_TOTAL_COUNT, true);
return solrTemplate.convertQueryResponseToBeans(solrServer.query(solrQuery), DomainType.class);
}
});
Please feel free to open an issue.

Native Query With Spring's JdbcTempate

I'm using spring's JdbcDaoSupport for making data base call. I want to execure native query (sql query) for retrieving data. Do we have any API available in JdbcTemplate for native query? I used queryForObject but it throws exception if there is no data whereas i was expecting it to return back null if it couldn't find data.
There are many options available for executing native sql with JdbcTemplate. The linked documentation contains plenty of methods that take native sql, and usually some sort of callback handler, which will accomplish exactly what you are looking for. A simple one that comes to mind is query(String sql, RowCallbackHandler callback).
jdbcTemplate.query("select * from mytable where something > 3", new RowCallbackHandler() {
public void processRow(ResultSet rs) {
//this will be called for each row. DO NOT call next() on the ResultSet from in here...
}
});
Spring JdbcTemplate's queryForObject method expects your SQL to return exactly one row. If the there are no rows returned or if there are more than 1 row returned it will throw a org.springframework.dao.IncorrectResultSizeDataAccessException. You will have to wrap the call to queryForObject with a try catch block to handle IncorrectResultSizeDataAccessException and return null if the exception is thrown
e.g.
try{
return jdbcTemplate.queryForObject(...);
}catch(IncorrectResultSizeDataAccessException e){
return null;
}

Resources