I want to sum the values of a column price.value where the column validatedAt is between startDate and endDate.
So I want a BigInteger as a result (the sum value).
This is what I tried:
final List<AggregationOperation> aggregationOperations = new ArrayList<>();
aggregationOperations.add(Aggregation.match(where("validatedAt").gte(startDate).lt(endDate)));
aggregationOperations.add(Aggregation.group().sum("price.value").as("total"));
final Aggregation turnoverAggregation = Aggregation.newAggregation(OrderEntity.class, aggregationOperations);
return this.mongoOperations.aggregate(turnoverAggregation, OrderEntity.class, BigInteger.class).getUniqueMappedResult();
This doesn't work. I have this error:
{"exception":"com.application.CommonClient$Builder$6","path":"/api/stats/dashboard","message":"Failed to instantiate java.math.BigInteger using constructor NO_CONSTRUCTOR with arguments ","error":"Internal Server Error","timestamp":1493209463953,"status":500}
Any help?
You don`t need to add a new pojo for just for this. It is helpful when you more fields to map and you want spring to map them automatically.
The correct way to fix the problem is to use BasicDBObject because MongoDB stores all values as key value pairs.
return this.mongoOperations.aggregate(turnoverAggregation, OrderEntity.class, BasicDBObject.class).getUniqueMappedResult().getInt("total");
Sidenote: You should use Double/BigDecimal for monetary values.
I resolved this problem by creating a class that has a BigInteger attribute:
private class Total {
private int total;
}
return this.mongoOperations.aggregate(turnoverAggregation, OrderEntity.class, Total.class).getUniqueMappedResult();
Related
I'm facing problem while converting Big Decimal to Integer.
My process description is, First I will be sending List of Integers into a DAO method to validate whether the integers are valid to proceed further. Then the valid List of Integers are processed in another place.
Core process
List<Integer> payments = DAO.checkStatus(payments); //payments is List of Integer
if(payments!=null){
//Do some other operation
DAO.changeStatus(payments); //Here payments is List of Integer which we got from above
DAO method implementation
checkStatus(List<Integer> payments){
List<Integer> FinalPayments = null;
//I have Hibernate query to get the details from Database
String HQL_Query = "select A.PY from T_Status A where A.status = 4 and (A.PY=:payments)";
Query query = session.CreateQuery(HQL_Query);
FinalPayments = query.list();
return FinalPayments;
}
In the DataBase PY column is a BigDecimal one. In table its defined as NUMBER. type. While execution of the query i'm getting BigDecimal values for FinalPayments list. There was no error/exception. The BigDecimal value is returned properly.
In core process, after the 1st method:
if(payments!=null){
//we're doing something with List of Integer payments right?
//It is passed to 2nd method.
changeStatus(List<Integer> FinalPayments){
String HQL_Query="update T_Status A set A.status = 6 where (A.PY:=FinalPayments)";
Query query = session.CreateQuery(HQL_Query);
query.setParameter("FinalPayments", FinalPayments); //Here i'm getting error
List<Integer> paymentsAfter = query.list();
}
The error is:
cannot cast java.math.BigDecimal to java.lang.Integer
Between 1st and 2nd method i tried to convert BigDecimal to Integer. But can't convert Integer list to Integer again.But i need those to be in the format of Integer to process 2nd method. Please help on this..
Use the intValue() method on your BigDecimal object to get its int value.
I'm not sure I understand your question but if you have a BigDecimal and you want a Integer you can use either intValue of intValueExact.
E.g.
List<BigDecimal> decimals = ...
List<Integer> ints = decimals.stream().map(BigDecimal::intValue).collect(Collectors.toList());
I have a bucket on riak in which I store simple Timestamp -> String values in this way:
val riakClient = RiakFactory.newClient(myHttpClusterConfig)
val myBucket = riakClient.fetchBucket(name).execute
myBucket.store(timestamp.toString, value).withoutFetch().w(1).execute
What I need to do now is to add an index on the keys. I tried defining a Java POJO in this way:
public class MyWrapper {
#RiakIndex(name="timestamp_index")
#RiakKey
public String timestamp;
public String value;
public MyWrapper(String timestamp, String value) {
this.timestamp = timestamp;
this.value = value;
}
}
and then running
myBucket.store(new MyWrapper(timestamp.toString, value)).withoutFetch().w(1).execute
The problem of this approach is that in riak the actual value is stored as a json object:
{"value":"myvalue"}
while I would simply need to store the myvalue string. Is there any way to achieve this? I can't see any index(name) method when executing store, and I can't see any annotations like #RiakKey but for values.
You can create a RiakObject using a RiakObjectBuilder, and then add the index on that:
val obj = RiakObjectBuilder.newBuilder(bucketName, myKey)
.withValue(myValue)
.addIndex("timestamp_index", timestamp)
.build
myBucket.store(obj).execute
If I understand what you are trying to do, you want the key/value pair "1403909549"/"Some Value" to be indexed by timestamp_index="1403909549" so that you can query specific times or ranges of times.
If that is the case, you do not need to explicitly add an index, you can query the implicit index $KEY in the same manner you would any other index.
Since all keys that Riak stores in LevelDB are indexed implicitly, I don't think a method was exposed to index them again explicitly.
I've got a setup with Spring & Hibernate over MySQL.
I have a MySQL Stored-Procedure I would like to call.
The procedure takes 2 float arguments, and returns a result-set with 3 fields. Integer,Integer,Float.
I created a class which extends spring's StoredProcedure.
This is the execute function:
public Map execute(float longitude, float latiude) {
Map inparams = new HashMap(2);
inparams.put("longitude", (float) longitude);
inparams.put("latitude", (float) latiude);
Map out = execute(inparams);
The problem is that I don't know how to parse the map result.
When I'm debugging, I see that all the result-set is in there, but It arranged in a strange way, and I don't know how to extract the fields.
The best I can do to show you how it looks, is to give you the toString() of out (Map)
Here it is:
{#result-set-1=[{id=4, out1=100, distance=40.9}, {id=5, out1=100,
distance=47.7}, {id=6, out1=100, distance=22.3}, {id=7, out1=100,
distance=27.4}, {id=8, out1=100, distance=22.1}, {id=9, out1=100,
distance=18.3}, {id=10, out1=100, distance=20.1}, {id=11, out1=100,
distance=28.6}, {id=12, out1=100, distance=23.1}], #update-count-1=0}
I'd look in a debugger to see what the types are; IntelliJ could tell me this easily.
It looks like a Map<String, Object> to me. The keys are "#result-set-1" and "#update-count-1".
The value for the first key is a List of Maps, one Map per row returned. The keys are the column names and the values are the returned values.
The value for the second key is an Integer; it's zero because you did a SELECT.
So, in the interest of spelling it out, here's how to extract your results (sorry for the initial coding error):
// Foo is some unknown object that encapsulates each row.
List<Foo> results = new ArrayList<Foo>();
Map<String, Object> rows = (Map<String, Object>) out.get("#result-set-1");
for (Map row : rows) {
int id = row.get("id");
int out1 = row.get("out1");
double distance = row.get("distance");
results.add(new Foo(id, out1, distance));
}
return results;
Since you are using Spring you can use the Jackson ObjectMapper.
It's more simple than the first answer.
class Foo {
private int id;
private int out1;
private double distance;
// getters and setters
}
ObjectMapper objectMapper = new ObjectMapper();
List<Foo> list = objectMapper.convertValue(execute.get("#result-set-1"), new TypeReference<List<Foo>>() {});
I hope that helps even if this question is open for a long time :)
Using Hbase API (Get/Put) or HBQL API, is it possible to retrieve timestamp of a particular column?
Assuming your client is configured and you have a table setup. Doing a get returns a Result
Get get = new Get(Bytes.toBytes("row_key"));
Result result_foo = table.get(get);
A Result is backed by a KeyValue. KeyValues contain the timestamps. You can get either a list of KeyValues with list() or get an array with raw(). A KeyValue has a get timestamp method.
result_foo.raw()[0].getTimestamp()
I think the follow will be better:
KeyValue kv = result.getColumnLatest(family, qualifier);
String status = Bytes.toString(kv.getValue());
Long timestamp = kv.getTimestamp();
since Result#getValue(family, qualifier) is implemented as
public byte[] getValue(byte[] family, byte[] qualifier) {
KeyValue kv = this.getColumnLatest(family, qualifier);
return kv == null ? null : kv.getValue();
}
#codingFoo's answer assumes all timestamps are the same for all cells, but op's question was for a specific column. In that respect, similar to #peibin wang's answer, I would propose the following if you would like the last timestamp for your column:
Use the getColumnLatestCell method on your Result object, and then call the getTimestamp method like so:
Result res = ...
res.getColumnLatestCell(Bytes.toBytes("column_family"), Bytes.toBytes("column_qualifier")).getTimestamp();
If you want access to a specific timestamp you could use the getColumnCells which returns all cells for a specified column, but then you will have to choose between the cells with a get(int index) and then call getTimestamp()
result_foo.rawCells()(0).getTimestamp
is a good style
Apache XMLBeans can be used to generate Java classes and interfaces from XML Schema Definition files (XSD). It also generates Enums based on StringEnumAbstractBase and StringEnumAbstractBase.Table to represent domain values. They are handy for entering only valid values. However, I want to get all those values to generate a JCombobox, a JTable or a html table.
Is there a XMLBeans API call to get all Enum values from a generated class?
Is the only choice available some sort of Java reflection?
Thanks
This worked for me:
for (int i = 1; i <= MyEnum.Enum.table.lastInt(); i++)
{
System.out.println(MyEnum.Enum.forInt(i));
}
Here is another way to get it :
public static List<String> getEnumValueList(XmlString xmlString){
List<String> values = new ArrayList<String>();
SchemaStringEnumEntry valArr[] = xmlString.schemaType().getStringEnumEntries();
for(SchemaStringEnumEntry val : valArr){
values.add(val.getString());
}
return values;
}
So, to get the list of enum values of ModelType, I do the following :
getEnumValueList(ModelType.Factory.newInstance());