How to write QueryBuilder Query for update Collections(Set) in Cassandra - java

I want to write QueryBuilder query for the following CQL command in java.
UPDATE category_utility
SET imageurls = imageurls + {'http://image1.jpg','http://image2.jpg','http://image3.jpg'} WHERE category_title = 'cat1';
In JAVA, I try with this following. I do not know how to write add in set operation in QueryBuilder command .
public void addImageList(ArrayList<String> list, int categoryId) {
Statement = QueryBuilder.update("category_utility").with(QueryBuilder.set("imageurls", list.toString())).where(QueryBuilder.eq("img_category_id", categoryId));
}

You want to use QueryBuilder.addAll(String, Set<?>), but that method takes a Set as a parameter, not an ArrayList.
So you need to modify your method as follows:
public Statement addImages(Set<String> imageurls, int categoryId){
return QueryBuilder.update("category_utility")
.with(QueryBuilder.addAll("imageurls", imageurls))
.where(QueryBuilder.eq("img_category_id", categoryId));
}

If you look at the QueryBuilder class there are add, addAll and remove, removeAll methods for handling set updates.

Related

Can I execute batch of queries using jpa/hibernate in a single shot?

Here is a sample code.
sourceFileItemNo and entityDplStatus are array of some values.
Query query;
for(int i = 0 ;(sourceFileItemNo!=null && i< sourceFileItemNo.length); i++){
Object[] parameters = {entityDplStatus[i],"1",sourceFileItemNo[i]};
String queryString = "UPDATE GtcEntityDetailsValue c SET c.dplStatus=?1 where c.referenceNo=?2 and c.itemNo=?3";
query = manager.createQuery(queryString);
query = setQueryParameters(query, parameters);
query.executeUpdate();
}
Here in this case we are updating the details each time in each iteration. Does JPA provides provision to add the queries to a list or something and execute all the queries in a single shot just like old connection statement execute batch?
Yes you can easily do it using hibernate,pass the list of objects with updated values that you want to persist, then just do:
private void updteRecord(List<Records> records){
int batchSize=10;
for(int i=0;i<records.size();i++)
{
getSession().saveOrUpdate(records.get(i));
if(i%batchSize==0)
{
getSession().flush();
getSession().clear();
}
}
}
The List of records you are feeding to this method should contain the values you need to upodate.

Realm java sort with multiple fields

I'm sorting like this:
RealmResults<Show> shows = realm.where(Show.class).findAll();
shows.sort("venueTitle", RealmResults.SORT_ORDER_ASCENDING);
How can I sort by multiple properties? Adding another sort line just resets the order of the results entirely.
Looks like they just added this in 0.77. I was using 0.76. Here's the Github issue:
https://github.com/realm/realm-java/issues/648
and here's the API reference:
http://realm.io/docs/java/0.77.0/api/
public void sort(java.lang.String[] fieldNames,
boolean[] sortAscending)
try below code
public RealmResults getSortedList(Class aClass) {
String []fieldNames={"field1","field2"};
Sort sort[]={Sort.ASCENDING,Sort.ASCENDING};
return realm.where(YourClass.class).findAllSorted(fieldNames,sort);
}

Query returning only empty value in java

I am using java to connect with oracle.This is the code which I have used
public List<FavouriteShop> getmyfavouriteshop(String username) {
List<FavouriteShop> res=null;
res = this.getJdbcTemplate().query("select * from(Select tbl_orderdetails.branch_name as myfavourite,tbl_orderdetails.branch_id as branch_id from tbl_orderdetails inner join tbl_ordermaster on tbl_orderdetails.order_master_id=tbl_ordermaster.ordermasterid where tbl_ordermaster.user_id='"+username+"' group by tbl_orderdetails.branch_name,tbl_orderdetails.branch_id order by count(tbl_orderdetails.branch_name) desc) where rownum<=3", new MyFavourite());
return res;
}
private class MyFavourite implements RowMapper<FavouriteShop> {
public FavouriteShop mapRow(ResultSet rs,int i) throws SQLException {
FavouriteShop g=new FavouriteShop();
g.setBranch_id(rs.getString("branch_id"));
g.setMyfavourite(rs.getString("myfavourite"));
return g;
}
}
I tried to execute same query in oracle I am getting output but not here and I am getting only empty result.
First, you have a possible SQL injection. You can avoid this by giving username as an argument to query
this.getJdbcTemplate().query("select * from (... where tbl_ordermaster.user_id=? ...) where rownum<=3",
new Object[]{ username }, new MyFavourite());
A possible reason for the empty result might be
... where tbl_ordermaster.user_id='"+username+"' ...
Usually, user_id is an integer value, but you compare it to a String and enclose it in quotes. Passing username as an argument to query as shown above, should already take care of this.
Usually it is not the same query or not the same database :)
Extract your query text to separate variable, print it to logs. Then copy-paste from logs to sql developer.
And check database and user name.
Also, it is possible that you inserted that entries but forgot to add COMMIT.

Inc/dec mongotemplate, atomically

I am trying to update one value of my document atomically using findAndModify, which according to my reading is atomic in the same document. According to my Unit test the values are not modified.
I'm using mongoTemplate in Java, and my code looks like
public OfferConfiguration IncreaseStock(OfferConfiguration offerConfiguration) {
Query query = new Query(Criteria.where("_id").is(offerConfiguration.getId()));
Update update = new Update().inc("stock", 1);
return mongoTemplate.findAndModify(query, update, OfferConfiguration.class);
}
public OfferConfiguration findAndDecreaseStock(String offerId ) {
Query query = new Query(Criteria.where("_id").is(offerId).and("stock").gt(0));
Update update = new Update().inc("stock", -1);
return mongoTemplate.findAndModify(query, update, OfferConfiguration.class);
}
Stock has type Long, and I can see that when I use a criteria in the find:
Query query = new Query(Criteria.where("_id").is(offerId).and("stock").gt(0));
return mongoTemplate.findOne(query, OfferConfiguration.class);
It returns only the values whose stock is greater than 0.
Any idea what is wrong in my code?
FindAndModify will return the original document after making the update to it by default.
If you want to get back the modified document you have to pass it the optional new option.
It seems you already found that the way to do that is by adding returnNew(true) to the findAndModify command.

Hibernate setMaxResults paging

If I don't set setFirstResult(-) and recursively call criteria.setmaxresults(10) each time, will it automatically grab the next 10 items from the database?
No. You have to use criteria.setFirstResult(0) and page through yourself, something like this:
public List getCarters(final int firstResult, final int maxResults) {
final Criteria criteria = sessionFactory.getCurrentSession()
.createCriteria(SomePersistentClass.class);
.add(Restrictions.eq("name", "Carter"))
criteria.setFirstResult(firstResult);
criteria.setMaxResults(maxResults);
return criteria.list();
}
Of course, no. Criteria grabs data from database only when you call .list() or .uniqueResult()

Categories

Resources