There are two methods to filter realmResult in java by "string"
RealmResults data = realm.where(RasifalDTO.class).contains(keyString,valueString);
But what i want to do is filter the Result with Respect to integer so i tried:
RealmResults data = realm.where(RasifalDTO.class).contains(keyString,vauleInt+"");
But i get :
java.lang.IllegalArgumentException: Field 'rasifalType': type mismatch. Was INTEGER, expected [STRING].
If you want to filter the result by an attribute of the Realm Object which happens to be an integer. Then equalTo(String key,int value) is the way to go (Do not get confused with using contains(key string,value string) like i was ).
RealmResult data = realm.where(RasifalDTO.class).equalTo(keyString,valueInt).findAll();
Try using this:
RealmResults data = realm.where(RasifalDTO.class).contains(keyString,String.valueOf(vauleInt));
Related
I created an entity (Model or Data class) in a Spring-Boot (Kotlin) project which contains a field with the type Arraylist but when I send an array data in JSON format from Postman, the Array gets stored in the database as a long random string.
When I try to retrieve the data from the database I get the actual array, perfectly formated.
My question is why is an ArrayList stored in an H2 database like this???
Evaluation.kt
#Entity
data class Evaluation (
#Id val id : String,
val timeStamp : Long,
val symptoms : ArrayList<String>,
val travelHistory : Boolean,
val contactWithCovidPatient : Boolean,
val evaluatedBy : String,
var evaluationPercentage : String? = null,
#ManyToOne var user: User? = null
)
EvaluationController.kt
#RestController
class EvaluationController (val evaluationService: IEvaluationService) {
#PostMapping("evaluate/{userId}")
fun evaluateUser(#PathVariable userId : String, #RequestBody evaluation: Evaluation) : ResponseEntity<Evaluation> =
ResponseEntity.ok().body(evaluationService.addEvaluation(evaluation, userId))
}
Request Body JSON
{
"id":"e_01",
"timeStamp":"123456789",
"pinCode":"123457",
"travelHistory":true,
"contactWithCovidPatient":true,
"evaluatedBy":"u_01",
"symptoms": ["Fever","Cough"]
}
Response JSON
{
"id": "e_01",
"timeStamp": 123456789,
"symptoms": [
"Fever",
"Cough"
],
"travelHistory": true,
"contactWithCovidPatient": true,
"evaluatedBy": "u_01",
"evaluationPercentage": "95",
"user": {
"id": "u_01",
"name": "abc01",
"phoneNumber": "9876543210",
"pinCode": "123457",
"covidResult": "Positive"
}
}
H2 Database Table
This is a hex string representing the serialized ArrayList object. See Serializable Objects for details about object serialization in Java.
Running the following code yields the same result:
List<String> symptoms = new ArrayList<>(Arrays.asList("Fever", "Cough"));
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(symptoms);
byte[] serializedObject = byteArrayOutputStream.toByteArray();
String hex = Hex.encodeHexString(serializedObject); // Apache Commons Codec
System.out.println(hex);
aced0005737200136a6176612e7574696c2e41727261794c6973747881d21d99c7619d03000149000473697a657870000000027704000000027400054665766572740005436f75676878
The raw string seen in the DB is a serialized object.
One way of implementing this is to first join your string ArrayList into one delimited string, but I highly recommend against this.
In general it's bad practice to put a list into a single field of a table. What you should be doing is creating a separate table for Symptoms with a one-to-many relationship with Evaluation.
You need to be aware of denormalization while designing your objects when using JPA. In your case, consider the following questions :
What happens if you want to query evaluations with specific symptoms?
What happens if you want to query a list of all the symptoms?
What happens if you want to expand symptoms with some other detail, such as date when a symptom appeared?
If you are ever in a situation of trying to add a collection of something into a database field 99.9999% of the time you're doing it wrong. Symptoms should be their own entity, and you have a one-to-many or many-to-many relationship between evaluation and symptom, depending on what you require.
Edit :
To clarify my answer further, when designing object classes think about whether a field is a value object or an entity. A value object is something that cannot be broken down further and can be represented by a primitive, such as Date, String, Int, etc. Some examples could be an object ID, name, phone number, etc.
An entity is an object that can be expanded further, like the Evaluations object you created. Within Evaluations you have a list of Symptoms, and you're treating Symptoms as a value object. Is it a value object though? I can immediately think of some additional fields you could put into a Symptom object, and by denormalizing symptoms the way you did, you are also inputting tons of duplicate data into the database.
An evaluation object containing ["Fever", "Cough"] in your implementation will be input into the database as one field. But another evaluation object containing the same symptoms will be input into the database for that evaluation because you don't have a foreign key dependency or a separate table representing symptoms. On top of not being able to query symptoms in relation with evaluations, or not being able to query symptoms on their own.
Is there any way to convert the string below to a list?
This string is retrieved after scanning a QR code.
CashRequest{
orderid='0',
user_id='nvHt2U5RnqUwXB4ZK37Zn1DXPV82',
userName='username',
userEmail='whateveremailthisis#email.blabla',
fullName='full name',
phoneNumber=0,
totalCash='$304.00',
totalRV='$34.00',
foods=[
Order{
userID='nvHt2U5RnqUwXB4ZK37Zn1DXPV82',
ProductID='-LMDiT7klgoXU8bQEM-4',
ProductName='Coke',
Quantity='4',
Price='1',
RedemptionPrice='10',
RedemptionValue='1'},
Order{
userID='nvHt2U5RnqUwXB4ZK37Zn1DXPV82',
ProductID='1000',
ProductName='Kunau Ring Ring Pradu',
Quantity='3',
Price='100',
RedemptionPrice='10',
RedemptionValue='10'
}
]
}
The desired output is to store it in firebase realtime database as below :
Well you have a few options. Since it is newline between values, you could use simple newline reads and compare if it starts with "reserved word that you are looking for" then substring from there, but that can get messy and a lot of bloat code.
The simplest way would be to do the known replace first.
Make a method that replaces all bad json keys with quote surrounded json keys like:
val myJsonCorrected = yourStringAbove.replace("Order", "\"Order"\")
repeat for all known entities until you have made it into valid json. Single ticks are fine for the values, but the keys need quotes as well.
Then simply create an object that matches the json format.
class CashRequestModel{
#SerializableName("orderid")
var orderID: Int? = null
etc.....
#SerializableName("foods")
var myFoods: ArrayList<OrderModel>? = null
}
class OrderMode {
#SerializableName("userID")
var userID: String? = null
#SerializableName("ProductID")
var userID: String? = null
etc..
}
Then simply convert it to JSON
val cashRequest = getGson().fromJson(cleanedUpJson, classTypeForCashRequest);
and your done. Now just use the list. Of course it would be better if you could get valid JSON without having to clean it up first, but it looks like the keys are known and you can easily code string replaces to fix the bad json before casting it to object that matches the structure.
Hope that helps.
I am trying to query DynamoDB using mapper.query() function with FilterExpression.
I need to generate a generic function where I will just tell the attributes operator and value, and it will return the generic string. But I see, it is not completely possible.
new DynamoDBQueryExpression<T>()
.withFilterExpression("att = string_val")
This is possible but if I have an Integer filter, then I have to do like this :
new DynamoDBQueryExpression<T>()
.withFilterExpression("att = :filter")
.withValueMap(":filter", new AttributeValue().withN(String.valueOf(12)));
Can this be avoided ? I wish to put everything in the filter string.. Can dynamoDB itself recognise int/string attributes ?
Thanks in advance!
I'm trying to create a query with selects only the Entities with specific numeric value in their property but the following Filter returns an empty result
Filter tmpFilter = new Query.FilterPredicate("cost", Query.FilterOperator.EQUAL, 10);
I have several entities that should be selected, I have tried to send the "10" as a string but still no luck.
When I try to select with GREATER_THAN or other filter operators then it works.
I have tried to run EQUAL on a string value and it worked but not on a numeric value.
Any ideas ?
Integer values are stored as Long in the Datastore. Try 10L instead of 10.
I am using the below mentioned MongoDB query in Java to find the maximun value of field price:
DBCursor cursor = coll.find(query,fields).sort(new BasicDBObject("price",1)).limit(1);
fields argument passing to coll.find function here is having the price field only.
So I am getting the output in the form:
{"price" : value}
Is there any way to get value only in the output without the field name and braces etc, so that it can be assigned to a variable or returned to the calling function etc.
Or if there is any other query or mechanism available that I can use for the same purpose.
Pls suggest..
Thanks & Regards
You can get value of price from the DBCursor object as follows.
while (cursor.hasNext()) {
Double price = (Double) cursor.next().get("price");
}
On the mongo shell you can do it as follows :
db.priceObj.find({},{_id:0, price:1}).sort({price:-1}).limit(1)[0].price
You cannot do this due to the fact that MongoDB communicates using BSON.
A single value like you want would be invalid BSON. It is easy enough to filter it out your side.