Firstly I want to say, I really liked Stackmob.
But I've got some little problems because I'm a newbie on stackmob.
I'm developing on Android sdk
I have created a schema called "level" and it has 2 unique indexes (facebook_id and level_no)
My question is how to insert, update and delete (crud) the rows by facebook_id and level_no.
(ps: I can update a schema if it has 1 unique index but when index counts are greater than 1, I dont know how to do it.)
An index isn't like a primary key; it doesn't enforce uniqueness, it just speeds up querying on those fields. You still have to think in terms of level_id as your primary key. It's not hard to do CRUD operations in terms of other fields though. For insert, if you leave out the primary key, one will be generated for you. For the other operations, you can query by the field you want:
Level.query(Level.class, new StackMobQuery().fieldIsEqualTo("facebook_id", "foo"), new StackMobQueryCallback<Level>() {...});
then once you've got your Level object, simply resave or delete
myLevel.setSomething("bar");
myLevel.save();
// or
myLevel.delete();
If you're using the datastore api, it's the same idea, you're just making the REST API calls directly.
Related
I need to synchronize the data in my application. I do the request to the server, bind and use copyToRealmOrUpdate(Iterable<E> objects) to add or update this data to the database.
But my files can be invalidated and I need something to delete everything that don't have at the data that return at the request. I don't want to truncate or do a manual delete to do this because performance matters.
IDEA 1
#beeender
What do you think about use the PRIMARY_KEY of the table to delete the data that I don't want (or I don't need)?
Looks like:
1º: If the database was populated, get all primary key and add it in an HashMap (or anything that do the same).
2º: Update the data or add, removes the item of the HashMap (using the primary key) if it was updated or added.
3º: Remove all items of HashMap on the Realm.
Maybe the In memory Realm would be a good choice for you in this situation. You can find related documents here .
By using the in-memory Realm:
The db will be empty when you start a new app process
After you close all the instances of the Realm, the data will be cleared as well.
----------------------------------- Update for deleting data for normal case -----------------------------------------
For deleting, there are some options you can use
Remove all data for a specific model, see doc
realm.allObjects(MyModel.class).clear();
Remove entire data from a given Realm by (Realm API)[https://realm.io/docs/java/latest/api/io/realm/Realm.html#deleteRealm(io.realm.RealmConfiguration)] (close all instances first!):
Realm.deleteRealm(realmConfig);
Or just remove the Realm file through normal java API.
If you really care about the performance, you could consider to separate those data in one Realm, and use option 2 or 3 to remove them. See doc here for using different Realm through RealmConfiguration.
----------------------------------- Update for delete by Date field ------------------------------------------------------
For your user case, this would be a good choice:
Add a Date field to your model, and add annotation #Index to make query faster on it.
Update/add rows and set the modified date to current time.
Delete the objects where its modifiedDate is before the current date.realm.where(MyModel.class).lessThan("modifiedDate", currentDate).findAll().clear()
NOTE: "The dates are truncated with a precision of one second. In order to maintain compatibility between 32 bits and 64 bits devices, it is not possible to store dates before 1900-12-13 and after 2038-01-19." See current limitations. If you could modified the table in a very short time which the accuracy doesn't fit, consider to use a int field instead. You can get the column's max value by RealmResult.max()
i am really stuck at this point of my android app development.
What i need is a way to save a changing amount of int or string-values (in a sql database). Yet im not even sure if this is the right approach, but let me explain:
In the app i am currently working on, you are able to create certain "events". Users should be able to apply for such events.
I have an external database with 2 tables:
first one for users - every user has a unique ID
second one for events - every event has a unique ID
I need each event to know what users applied for it. And i need each user to know what events they applied for.
I was thinking to save the Event-IDs in the User-Table and vice versa.
I just dont know how to do that since the amount of applicants/ID's can change. Is there a way to save Arrays in the database which can easily be edited (e.g. +/- one ID) and read?
Is this even the right way? I am very happy for any advise!
Thanks in advance!
What you seem to want is a many-to-many relationship. A user can be part of many events, and an event can have many users. That requires an additional table though:
Table: User Columns: UserId, Name, ...
Table: Event Columns: EventId, Name, ...
Table: UserEvents Columns: UserId, EventId, ...
In the new table, UserEvents, you would store the UserId's and EventId's like this:
UserEvents
UserId EventId
1 1
2 1
1 2
This means that if you selected UserId 1, the query would return EventId 1 & 2. If you selected EventId 1 the query would return that UserId 1 & 2 would be attending.
This is the standard and recommended way to deal with many-to-many. It's very flexible and can easily be scaled.
You could either use a Compound key (Composite Key) for this table, or create a column specifically as a Primary Key. The code below can be used, and manipulated, to create both your table and Compound/Composite key (I'm guessing on data types).
CREATE TABLE UserEvents
(
[UserId] INT NOT NULL,
[EventId] INT NOT NULL
CONSTRAINT PK_UserEvents PRIMARY KEY NONCLUSTERED ([UserId], [EventId])
)
I would add a third table (e.g. UserEvents) to store which events a user has applied for, along with other relevant attributes (e.g. ApplicationTime, ApplicationStatus). This association would have a foreign key relationship back to the related tables and resolve the many-to-many relationship between users and events.
What you have there is called a "many-to-many" relationship between to tables which can only be resolved by the introduction of a third table between your two tables that stores the associations.
This table would contain the User-ID and the Event-ID as foreign keys (and maybe additional information).
I am new in programming, and I want to ask question regarding database schema (I'm using SQLite Database for Android Development)
I have some table, let say :
MsMember
MemberId
Password
MsGroup
GroupId
GroupName
MsAnnouncement
AnnouncementId
AnnouncementName
MsComment
CommentId
CommentContent
MsTodolist
TodolistId
TodolistTitle
And I want everytime a new row has been inserted to (at least one of) all five tables above, it will create a notification to user, as far as I know, with this concept, I should create a table to store every detail of notification then shows it to user..
And my best opinion so far is I create a table let say MsNotification, then to connect all five tables with this MsNotification I should have foreign key referring to each table..
My Question is would it be possible (and effective) to have a column that has more than one references?
Example :
Foreign key (SourceId) Referring MsMember (MemberId),
Foreign key(SourceId) referring MsComment (CommentId),
Foreign key (SourceId) referring MsAnnouncement (AnnouncementId), and so on.
or is there any better way to implement this concept?
Thank you in advance
No ,you can not assign single foreign key to multiple column .
But you can put multiple foreign key in single table
I'm trying to think of how to get around this problem. I have an ORMlite object that can belong to multiple Categories; I'm using another table (i.e. a ForeignCollection) to track many-to-many connections between my objects and categories.
The problem is if I update the object with changed categories, the new categories are added, but old ones are not removed.
In the JavaDoc for the update method of DAO I see this text:
NOTE: Typically this will not save changes made to foreign objects or
to foreign collections.
My question is about the use of the word "typically." Does this mean that there IS a way through some sort of setting to make sure that updates update related foreign objects/collections?
Or should I read the sentence as if "typically" was not there, assume there is no automatic method, and that I need to run extra queries on committing each object to delete old categories?
The problem is if I update the object with changed categories, the new categories are added, but old ones are not removed.
So you have an object that has a foreign collection of categories:
#ForeignCollectionField
ForeignCollection<Category> categories;
If you run categories.add(category1) or categories.remove(category1), then the underlying collection should remove those from its associated table using a built-in DAO.
If you are changing the category list some other way then you are going to have to remove the Category entries by hand using the categoryDao directly.
... about the use of the word "typically." Does this mean that there IS a way through some sort of setting to make sure that updates update related foreign objects/collections?
Not sure why I left the word "typically" there. I think it was a blanket statement to take into account the various auto-create, auto-refresh, etc. field settings -- I'm not sure. In any case, I've removed it from the code base.
ORMLite has no way to know if foreign objects have been changed. It does not create magic proxy objects nor sessions so that it can tell when a foreign object has been updated. You have to be explicit about what you want updated when. The documentation on foreign collections is quite explicit about it.
OrmLite will not save objects to ForeignCollections automatically. You have to store and delete these objects yourself. Ormlite will retrieve the objects in the ForeignCollection automatically for you, provided you set the right parameters in the annotation.
Ormlite is "lite". It does ORM, but not completely. It's not JPA or Hibernate.
I solved this problem by adding the new Category to the table Categories directly, instead of adding a new category to the Object's foreignCollection.
This can be done by simply creating a category ado and adding a new element.
A newCategory.setObject(object) is needed in order to create the relation with the object.
Hope this helps.
I am fetching my data with id which is Integer primary key or integer.
But after deleting any row...
After that if we make select query to show all.
But it will give force close because one id is missing.
I want that id can itself take auto increment & decrement.
when i delete a record at the end(i.g. id=7) after this i add a row then id must be 7 not 8. as same when i delete a row in middle(i.g. id=3) then all the row auto specify by acceding.
your idea can help me.
Most systems with auto-incrementing columns keep track of the last value inserted (or the next one to be inserted) and do not ever reissue a number (give the same number twice), even if the last number issued has been removed from the table.
Judging from what you are asking, SQLite is another such system.
If there is any concurrency in the system, then this is risky, but for a single-user, single-app-at-a-time system, you might get away with:
SELECT MAX(id_column) + 1 FROM YourTable
to find the next available value. Depending on how SQLite behaves, you might be able to embed that in the VALUES list of an INSERT statement:
INSERT INTO YourTable(id_column, ...)
VALUES((SELECT MAX(id_column) + 1 FROM YourTable), ...);
That may not work; you may have to do this as two operations. Note that if there is any concurrency, the two statement form is a bad ideaTM. The primary key unique constraint normally prevents disaster, but one of two concurrent statements fails because it tries to insert a value that the other just inserted - so it has to retry and hope for the best. Clearly, a cell phone has less concurrency than, say, a web server so the problem is correspondingly less severe. But be careful.
On the whole, though, it is best to let gaps appear in the sequence without worrying about it. It is usually not necessary to worry about them. If you must worry about gaps, don't let people make them in the first place. Or move an existing row to fill in the gap when you do a delete that creates one. That still leaves deletes at the end creating gaps when new rows are added, which is why it is best to get over the "it must be a contiguous sequence of numbers" mentality. Auto-increment guarantees uniqueness; it does not guarantee contiguity.