Can i exclude two columns from clearing in Realm Database?
when i use realm.clear(City.class).
For example i don't want to clear data on name and location columns
When using clear method
I want to save it from clearing
No, you cannot do that. First, Realm.clear() is renamed to Realm.delete().
Basically the purpose of this API is to delete all the elements which are the type of given class. It is NOT set the default values to all the fields of those elements.
For your use case, you need to iterate and call set all values manually. Something like:
RealmResults<City> results = realm.where(City.class).findAll();
for (City city : results) {
city.setName(null);
city.setZipCode(0);
}
Related
I want to show data in vaadin's grid, but I want to create columns dynamically for each value from customAttributes list. My data model more or less look like this
Item
name: String
localization: Localization
visible: Boolean
customAttributes: List<CustomAttribute>
CustomAttribute
name: String
value: String
Each Item has the same set of attribute types, only the values are different. User can manually defined new attribute types.
How can I create this grid?
Currently I do it in this way:
grid.setColumns("name", "visible");
grid.addColumn(v -> v.getLocalization().getName()).setHeader("Localization");
But I have no idea for dynamic creating columns for each custom attribute.
Like it was already written in the comments, you can loop over the attribute names assuming your have a list (or set) of them. One small gotcha is that you need to do that in a way that ensures values inside the callback are effectively final.
attributeNames.forEach(name -> {
grid.addColumn(item -> item.getCustomAttributes().get(name))
.setHeader(name);
});
If you don't directly know the attribute names but you're loading all items into memory instead of lazy loading them, then you can find the unique names by iterating over all items:
items.stream().flatMap(item -> item.getCustomAttributes().keySet().stream())
.distinct().forEach(<same loop as in the previous example>);
I have the following function in my repository
Set<Felhasznalo> findAllByNevContainsIgnoreCase(String nev);
When I use this function in the controller I got back one User.
For example, if I have a String "John" and I call the repo function with that string I got back "John Doe" but I also have "John Doe Jr" in the db and I need him too.
Why I get only one User?
I see you are using a Set. Maybe you have implemented an equals() function which checks the names and the Set filters out duplicate elements.
Try changing your code to this:
List<Felhasznalo> findAllByNevContainsIgnoreCase(String nev);
So use a List.
This is because you are storing your result in a Set which does not allow any duplicate values but here, you have duplicate names. Try changing Set to List as:
public List<Felhasznalo> findAllByNevContainsIgnoreCase(String nev);
A little backstory. I am working on a java project, using spring data, and i need to log all changes made to all entities and what type of change (event type) it is (eg. INSERT, UPDATE, DELETE) in mongodb, in an automated way.
For this i am using hibernate postEventListeners (PostInsertListener, PostUpdateListener and PostDeleteListener). This was all good, but now a change has been made to the original requirement, and i need to create a few more event types ( for example LOGIN ).
To create the LOGIN event, without completely altering the existing code, i found that i can just have a simple check, to see if the entity that i'm processing is a User and if the only property that is changed is lastLogin.
if (entity instanceof User) {
if(updateEvent.getDirtyProperties().length == 1 && updateEvent.getDirtyProperties()[0] == 8)
history.setEventType(HistoryEvent.LOGIN);
}
updateEvent is an instace of PostUpdateEvent, from the onPostUpdate function.
This is working fine, but my current implementation is not ideal. In hibernate, getState() and getOldState() return and Object[] that contains all the properties of the object that is being updated. getDirtyProperties() returns the an array of indexes, indexes of only the properties which are not the same in the getState and getOldState arrays.
The problem that i have is that the Object[] returned by getState and getOldState contains only the values of the properties, and i can't figure out the order that they are in. For now i just hardcoded the index, but this solution is not ideal, because if i add/remove a property from the User class, the index also gets modified, and i have to find out what the new index is and change it.
My question is, what order are the properties in the Object[], or how can i change my code so that the value is not hardcoded? Is there a way to get a pair, of property value instead of getting just an array of values?
So i actually found the answer on a hibernate forum.
I'l leave the link to give credit to Vlad Mihalcea
Answer here
To get the property names use this:
String[] properties = event.getPersister().getPropertyNames();
Then match the array indexes and you’ll know what property has
changed.
I have some data that contains a STATE field (String/Text) that defines what state a given request is currently in (e.g. pending, approved denied etc.) and to get all the unique values from that column I can run the following TSQL query
SELECT DISTINCT STATE FROM CALLOUT_REQUEST
where CALLOUT_REQUEST is my table name and STATE being the field which returns something like:
STATE
approved
denied
pending
...
However I don't understand how I would turn that into a query in my repository as it seems I need a "by" statement or some other filter mechanism which i can get the STATE based on?
What I am looking to return - as shown in the raw TSQL query above - is some kind of List or Array object which contains all the unique/distinct values in all of the STATE fields.
So in pseudo code i think i am looking for something like this:
String[] states = repository.findDisinctState();
where findDistinctState() would then return an array of sorts.
Hope that makes sense - I am very new to Java and Spring in general so I think I am missing some conceptual knowledge to utilise the above.
UPDATE:
The 'state' concept is closed so i could implement that as an enum - only problem is i dont know how to do that :) Ill look into how i can do that as i think it fits perfectly with what i am trying to achieve.
The List i get from the query provided is intended to be used to get a count of all the occurrences. I had this code before to get a total count for each of the 'states':
Map stats = new HashMap();
String[] states = {"approved", "denied", "pending", "deactivated"};
for (int i = 0; i < states.length; i++) {
stats.put(states[i], repository.countByState(states[i]));
}
Am i correct in understanding that the states Array that i have in the above code snippet could be turned into an enum and then i dont even need the custom #Query anymore?
If that state concept is closed - you know its possible set of values - it should be an enum.
After that you can create queries that you invoke like:
repository.findByState(State.APPROVED)
If you can't create an enum, you need a separate method to get the distinct values, which can't be provided by JPA, because you need a list of strings and not a list of CalloutRequests.
Then you need to specify a query manually like:
#Query("SELECT DISTINCT State FROM CALLOUT_REQUEST")
List<String> findDistinctStates();
You can use a JPQL query for this, with the #org.springframework.data.jpa.repository.Query annotation:
#Query("select distinct state from CalloutRequest")
List<String> findDistinctStates();
If you don't want to use #Query then one solution is there to create an interface "StateOnlyInterface" with method named "getState()".
Then create method in your repo with name, getDistinctState(). Return type of this method to be kept as ArrayList of StateOnlyInterface.
sorry for asking another really obvious question
I have a following string :
{
status=1,
msg=1 out of 2 Transactions Fetched Successfully,
transaction_details=
{2298597={mihpayid=403993715508098532, request_id=NULL, bank_ref_num=NULL, amt=53.77, disc=0.00, mode=CC, PG_TYPE=AXIS, card_no=512345XXXXXX2346, name_on_card=emu, udf2=0, addedon=2013-06-03 17:34:42, status=failure, unmappedstatus=failed, Merchant_UTR=NULL, Settled_At=NULL},
6503939={mihpayid=Not Found, status=Not Found}
}
}
and I want to group them in to a HashMap or to a ArrayList really don't know what to use if if give the transaction ids ex: 2298597 and 6503939 I should be able to get the other values like status etc.
I really don't know how to go about that is why ended up asking for help here.
Please help me with some inputs or if possible with sample code.
thanks
EDIT
I manage to put all values in to map and get values by keys now I am able to get values like the following :
transaction_details is the key
and Values : {2298597={mihpayid=403993715508098532, request_id=NULL, bank_ref_num=NULL, amt=53.77, disc=0.00, mode=CC, PG_TYPE=AXIS, card_no=512345XXXXXX2346, name_on_card=emu, udf2=0, addedon=2013-06-03 17:34:42, status=failure, unmappedstatus=failed, Merchant_UTR=NULL, Settled_At=NULL}, 6503939={mihpayid=Not Found, status=Not Found}}
now I have to group the values based the transactions numbers ex : 2298597 how do I go about ?
Create a Transactions class. Have all your variables and corresponding getters and setters. Override you .equals() and .hashCode() methods.
And as of what do choose between HashMap and List I would suggest go for HashMap as complexity for accessing data stored in HashMap is O(1). For List it is O(N)
As for me, you should create a datacontainer for your "string" (some sort of operation response right?) and put it into Map where keys would be your desired values (here some ids), and map's values would be just your datacontainer objects.
EDIT:
Map<String,MagicContainer> myMap=new HashMap<String,MagicContainer>();
MagicContainer message=new MagicContainer(message); // where message is lets say your example string
for(String singleId:message.getTransactionIDs()){
myMap.put(singleId,message);
}
//now you can get your message by one of transactions id
String status=myMap.get("2298597").getStatus();
Ofc. it is up to you to write logic inside MagicContainer class (message parsing and getters + setters to important values)
EDIT:
In such case as you pointed in your edit, simply wrap map's values into list eg. HashMap<String,List<MagicContainer>>(), and while adding to map, check for existance of corresponding key, and if it exists, simply add your message to the list. Create new key with new list otherwise.