Foreignfield no value Ormlite - android

I would like to ask assistance with using Ormlite. I have a class(Node.class) with fields-
#DatabaseField(generatedId = true)
public int id;
#DatabaseField
String path;
#DatabaseField
String label;
#DatabaseField
Date lastModified;
#DatabaseField
String resourceType = NODE_TYPE_ENTRY;
#DatabaseField
int status = NODE_STATUS_FRESH;
#DatabaseField
boolean leaf = false;
#DatabaseField
UUID uuid;
#ForeignCollectionField(eager = false)
public ForeignCollection<Node> children;
#ForeignCollectionField(eager = true)
public ForeignCollection<Property> properties;
#DatabaseField(foreign = true,index=true)
Node parent;
and another class(Classroom.class) with fields
#DatabaseField(generatedId=true)
int id;
#DatabaseField
String name;
#DatabaseField
String value;
#DatabaseField(foreign=true,index=true)
Node node;
My problem is that, when I add a property , the field node is always 0 and the result should be the id of the created node.
Hoping for your help.
Thanks

I think #k3v1n4ud3's comment is pointing you to the right answer.
You first need to insert the node into the Node table so the id field in the Node can be auto-generated and set on the node object. Then you can assign it to the node field in the Classroom so when you insert Classroom into the database, the node_id field will be non-0.
To quote the docs on "foreign objects" in ORMLite:
When you are creating a field with a foreign object, please note that the foreign object will not automatically be created for you. If your foreign object has a generated-id which is provided by the database then you need to create it before you create any objects that reference it.

Related

ORMlite how to add Collection<Collection<Double>>?

I have the following Class:
#DatabaseTable
public class BodyWeight implements Serializable {
#DatabaseField(generatedId = true, useGetSet = true, columnName = "id")
private Long id;
#DatabaseField
private String name;
#DatabaseField
private double goal;
#DatabaseField
private String primaryunit;
#DatabaseField
private String secondaryunit;
#DatabaseField
private int secondarysize;
#DatabaseField
private Collection<Collection<Double>> data;
How could I add a list of list of doubles primitives to database? What is the process? Should I create more classes for the List of list of doubles?
One possible way would be to keep Collection<Collection<Double>> data in your class and store it as JSON string in database with using custom persister. Like this
#DatabaseField(persisterClass = MyCustomPersister.class)
Collection<Collection<Double>> data;
Where MyCustomPersister should implement com.j256.ormlite.field.DataPersister or one of available implementations. Basically just two methods:
#Override
public Object resultToSqlArg();
#Override
public Object sqlArgToJava();
How could I add a list of list of doubles primitives to database? What is the process?
This is pretty complex. One way is just to make the type be serializable.
#DatabaseField(dataType = DataType.SERIALIZABLE)
private Collection<Collection<Double>> data;
That, like #unnamed_b's answer will store it in place as a serialized block of bytes. This won't work if you have a large number of doubles however.
If you want to store it as objects in another table then you are going to have to define these objects. Something like:
#DatabaseField(generatedId = true)
private long id;
#ForeignCollectionField
private Collection<DoubleCollection> data;
ORMLite only handles straight collections so we need to define the sub-collection:
#DatabaseTable
public class DoubleCollection {
#DatabaseField(generatedId = true)
private long id;
#ForeignCollectionField
private Collection<DoubleWrapper> data;
}
If you need to store a collection of doubles then you need to define a wrapper to hold an id and your double value.
#DatabaseTable
public class DoubleWrapper {
#DatabaseField(generatedId = true)
private long id;
#DatabaseField
private double value;
}

Ormlite foreign field giving me null on response and sometimes duplicate field

I'm having issue on joining tables on ormlite. On the first load i have my pojo ready for insertion of data from api using retrofit and gson as the tools.
Here's my pojos:
public class ParticipantDetailsModel {
#DatabaseField(id = true)
private int id;
#DatabaseField
private String first_name;
#DatabaseField
private String last_name;
}
public class Trainings implements Serializable {
#DatabaseField
private int participant_id;
#DatabaseField
private int batch_id;
#DatabaseField
private int graduation_program_id;
#DatabaseField
private int id;
#DatabaseField(foreign = true, foreignAutoRefresh = true, foreignAutoCreate = true)
private ParticipantDetailsModel participant;
}
On that Pojo i am actually getting duplicate field id which is "participant_id". So what i did is to rename this field from private ParticipantDetailsModel participant to private ParticipantDetailsModel participants, just for me to get the data. but once i query im not getting any values:
QueryBuilder<Trainings, String> qb1 = dao1.queryBuilder();
QueryBuilder<ParticipantDetailsModel, String> qb2 = dao2.queryBuilder();
qb1.where().eq("id", item.getId()).and().in("participant_id", parId);
List<Trainings> u = qb1.join(qb2).query();
do you have any idea what im missing?
heres my db:
enter image description here
Have a look at the Ormlite documentation
2.12 Foreign Object Fields
...
Notice that the name of the field is not account but is instead account_id. You will
need to use this field name if you are querying for it. You can set the column name using
the columnName field in the DatabaseField annotation
To set the columnName use:
public static final String ID_COLUMN = "ID";
#DatabaseField(columnName = ID_COLUMN)
private int id;
To make the query work, you have to set a Where clause on qb2 as well.
qb1.where().eq("id", item.getId());
qb2.where().in("id", parId);
List<Trainings> u = qb1.join(qb2).query();

Manually updating a foreign key.

I am pretty much aware of the absence of foreign keys in Realm. But I encountered this issue. I receive data in a normalised way and I have to figure out how to properly persist the relations.
Example:
class User{
private int id;
private Email email;
}
class Email{
private int id;
private String address;
}
And I receive something like:
{user={id:1, emailId:1}}
How can I store this type of data in my existing realm object ?
You will have to parse the JSON yourself to setup the links. From your description it isn't clear if you User and Email is already in Realm, but if that is the case I would do something like this:
class User{
#PrimaryKey
private int id;
private Email email;
}
class Email{
#PrimaryKey
private int id;
private String address;
}
JSONObject json = new JSONObject("{id:1, emailId:1}");
realm.beginTransaction();
User user = realm.where(User.class).equalTo("id", json.getInt("id")).findFirst();
Email email = realm.where(Email.class).equalTo("id", json.getInt("emailId")).findFirst();
user.setEmail(email);
realm.commitTransaction();

OrmLite foreign key exists from Json

I've never used OrmLite before but I need to edit an existing project that uses it.
I have two classes : Person and Office.
I'm using gson to parse, with the person an office Id is provided, for example office_id: "4456".
I was hoping it would be possible to link the two together from my Person class so I can easily get a office for a person.
For example:
#SerializedName("id")
#DatabaseField(id = true, columnName = ID)
private int mId;
#SerializedName("full_name")
#DatabaseField(columnName = FULL_NAME)
private String mFullName = null;
#DatabaseField(columnName = POSITION)
private String mPosition = null;
#SerializedName("email")
#DatabaseField(columnName = EMAIL)
private String mEmail = null;
private Office office = null;
#SerializedName("office_id")
private String officeId = null;
So I have the officeId from Json which is stored in the Person table. I would like to automatically load the Office into the Person object whenever it is loaded.
To automatically fetch a referenced object upon querying you can use foreignAutoRefresh = true in your #DatabaseField. You reference the Object and not the id itself. In the table, the id of the referenced row will be stored.
To clarify for your project:
Office must look something like this:
#SerializedName("id")
#DatabaseField(id = true, columnName = ID)
private int mId;
...
And your Person (database-wise) like this:
#DatabaseField(id = true, columnName = ID)
private int mId;
#DatabaseField(columnName = FULL_NAME)
private String mFullName = null;
#DatabaseField(columnName = POSITION)
private String mPosition = null;
#DatabaseField(columnName = EMAIL)
private String mEmail = null;
#DatabaseField(foreign = true, foreignAutoRefresh = true)
private Office office = null;
The Office column in the Person table will hold the id of the Office.
foreignAutoRefresh tells ORMLite to fetch the full Office upon querying the Person
http://ormlite.com/javadoc/ormlite-core/com/j256/ormlite/field/DatabaseField.html#foreignAutoRefresh()
Hope this helps

Problems saving Collection using ORMLite on Android

I have two class:
public class Questionnaire {
#DatabaseField(generatedId=true, useGetSet=true)
private Long id;
#DatabaseField
private int type;
#DatabaseField
private String title;
#DatabaseField
private String description;
#ForeignCollectionField(eager = true)
private Collection<Question> questions;
// Get and Set omitted
and
public class Question {
#DatabaseField(generatedId=true, useGetSet=true)
private Long id;
#DatabaseField
private int type;
#DatabaseField
private String description;
#DatabaseField(foreign = true, foreignAutoRefresh= true)
private Questionnaire questionario;
//get and set ommited
When I save a Questionnaire with a List of Questions. The objects are persisted, but I lose the relationship.
I save in this way:
ForeignCollection<Question> questions =
getDao(Questionnaire.class).getEmptyForeignCollection("questions");
for(Question question : DataUtil.getAllQuestions()) {
questions.add(question);
}
Questionnaire questionnarie = new Questionnaire();
questionnarie.setQuestions(questions);
questionnarie.setTitle("Normal");
questionnarie.setDescription("QuestionĂ¡rio normal");
getDao(Questionnaire.class).createOrUpdate(questionarie);
When I retrieved this register from database, a Question data doesn't have a reference for Questionnaire, and my Questionnaire doesn't have question list filled.
Any help will be appreciated.
The problem is that you are not setting the questionario field on your Question objects. The relationship is from the Question to the associated Questionnaire. There is nothing in the Questionnaire table that points the other way. See the documentation on foreign objects.
I would recommend doing something like the following:
Dao<Questionnaire, Long> dao = getDao(Questionnaire.class);
ForeignCollection<Question> questions =
dao.getEmptyForeignCollection("questions");
Questionnaire questionnarie = new Questionnaire();
questionnarie.setQuestions(questions);
questionnarie.setTitle("Normal");
questionnarie.setDescription("QuestionĂ¡rio normal");
dao.createOrUpdate(questionarie);
for(Question question : DataUtil.getAllQuestions()) {
// you must set the questionnarie field on the Question
// if it is a generated-id, it must be set _after_ it has been created
question.setQuestionnaire(questionnarie);
questions.add(question);
}

Categories

Resources