Save linked objects Primary key value already exists Relationships - android

I have just started to use RealmDB and cannot figure out how to save linked object correctly, to implement a sort of foreign key
Here is my main User model.
public class UserModel extends RealmObject {
#PrimaryKey
public Long id;
public String firstName;
public String lastName;
public UserSettings userSettingsModel;
}
UserSettings Model is defined as follows.
public class UserSettingsModel extends RealmObject {
#PrimaryKey
private Long id;
public String email;
public RealmList<Car> cars;
}
And Car is a model itself.
public class Car extends RealmObject {
#PrimaryKey
private Long id;
public String model;
}
The problem is that when I am trying to save UserModel it tries to recreate all objects assigned to it. So before I saving user model I have already creates some Car objects.
I don't need to create them, but to reference like the foreign key in SQL databases. And when I am retrieving a user from the database it should automatically load all related data by primary keys.
Is it possible to achieve such behavior using Realm ?

Thanks for help. Solved this problem by using the copyToRealmOrUpdate method instead of copyToRealm.

You should create a managed object using realm.createObject(clazz, pkValue); if it doesn't exist yet, then set it as value or add it to the RealmList that you get another managed object.
You can also create managed objects from unmanaged objects with copyToRealmOrUpdate() (if the object has a primary key).
And when I am retrieving a user from the database it should automatically load all related data by primary keys.
The RealmList allows access to the related objects, and in fact, is also queryable by calling .where() on it. However, this is not based on primary keys. That feature is tracked under "computed fields".

Related

How to implement Inner Join on Realm DB in android

I am searching everywhere but not found the exact way to use Inner Join on Realm DB in Android, check my code
public class UserName extends RealmObject {
private int UserID;
private String UserName;
// Getter Setters
}
public class UserDepartment extends RealmObject {
private int UserID;
private String UserDepartment;
// Getter Setters
}
In SQLite by using following query we easily get data
Select n.UserName, d.UserDepartment
FROM Name n INNER JOIN Department d
ON n.UserID=d.UserID
ORDER BY d.UserDepartment
But how to do same thing on Realm DB to get result...
Thanks in Advance!!
As you may know Realm is a non-relational database and concepts like join belongs for relational database. but if you need to have both UserName and UserDepartment in a single model class there are lots of implementations. but due to my experiences and according to realm constraints in using objects on different threads and updating objects snapshot with realm file, I suggest you to create a new entity, just like this:
class User extends RealmObject{
private int userId;
private UserName username;
private UserDepartment userDepartment;
}
whenever you insert a record into either UserName or UserDepartment you need to insert a record or update existing record in User.

Can i create object to object map inside Google firestore console?

I have following object:
public class Cart {
public String id;
public List<Map<Product, Double>> productsInCart;
}
In this key itself is a complex object, how to do it in firestore?
Also above object can be redesigned as following
public class Cart {
public String id;
public Map<Product, Double> productsInCart;
}
Firestore does not have any sense of "complex" keys or properties. Fields and nested object property names must be strings. If you need to store something more complex, you will need to somehow reduce it down to a unique string. One option is to use a hash of the data in the object, but you're better off redesigning your object to simply use strings as keys.

Confuse on dealing with relations between objects using Android Room

When using the android data-persistent library Android Room ,how can I directly insert the Comment Object into the database including all the field value, and how can I query all the value out as a Comment Object?
As I know, I can not use the Comment Object as a Entity in Room directory, because of the field replyComment is also a Comment Object. And I can not query out a Comment Object even I define a POJO using the #Relations annotation either because of the one-to-one relations and one-to-many relations all included in the Comment Object.
Is there any other way except changing the Comment Model definition, such as using foreign key, making a effect on insert action and query action?
public class Comment {
public String content;
public String id;
public Comment replyComment;
public User user;
public List<ImageMedia> images;
}
public class User{
public String id;
public String name;
}
public class ImageMedia{
public String key;
public String url;
}
Is there any other way except changing the Comment Model definition
No. You would need to create a set of entities that model the database structure, where children have foreign key columns pointing back to their parents:
CommentEntity has a foreign key back to CommentEntity for the reply
CommentEntity has a foreign key back to UserEntity
ImageMediaEntity has a foreign key back to CommentEntity

How to make a field auto increment in ActiveAndroid ORM

How can I make an integer or long field to be auto-incremented using annotation.
As we can read in a documentation:
One important thing to note is that ActiveAndroid creates an id field
for your tables. This field is an auto-incrementing primary key.
Maybe accessing auto-generated primary key will be enough for you?
Moreover, if you would like to create custom primary key in you model, you can check solution mentioned in GitHub issue connected with ActiveAndroid, which looks like this:
#Table(name = "Items", id = "clientId")
public class Item extends Model {
#Column(name = "id")
private long id;
}
Then, id field is custom primary key, which will be auto-incremented.
In case of ActiveAndroid ORM you do not need to write id column in model, It will automatic generate auto incremented value and you can simply use it.
I am giving a sample model below-
#Table(name="Items")
public class Item extends Model{
#Column(name="name")
public String name;
}
Instead of
#Table(name="Items")
public class Item extends Model{
#Column(name="Id")
public long id;
#Column(name="name")
public String name;
}
If item is an object of Item then you can simply get id by using
item.getId();
So, the correct model is first one. For reference you can click here.

ForeignCollection create or update

How do I create OR update a ForeignCollection in OrmLite?
If I try to simply add an object to a ForeignCollection, the add method acts as a create (insert into) method, but if the object already exists I will get an error about not having a unique primary key. I don't want duplicates to appear with autoincrementing primary keys, so this is fine to get this notice.
If I use the update method, then it will error if there is nothing to update.
It seems that the foreigncollection object doesn't have a way to tell me if an object is already existing in the database.
So is the only way to write a separate query myself, see if each object exists and drop the ones that have changed?
If you are using for example :
#DatabaseTable(tableName = "question")
public class QuestionDb implements Serializable {
#ForeignCollectionField(foreignFieldName = "question", eager = true)
private ForeignCollection<AnswerDb> answers;
}
#DatabaseTable(tableName="answers")
public class AnswerDb implements Serializable{
#DatabaseField (foreign=true,canBeNull=true,columnName=FIELD_QUESTIONID)
private QuestionDb question;
}
You will have to use the function createOrUpdate of the AnswersDB.
answerYouWantToAdd.setQuestion(yourQuestion);
answerDao.createOrUpdate(answerYouWantToAdd);

Categories

Resources