OrmLite foreign key exists from Json - android

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

Related

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();

Realm.io - Is it possible to find object by its subobject?

Doctor includes object Organization sub object:
#PrimaryKey
private int doctorId;
private FullName fullName;
private Age age;
private Organization organization;
private Position position;
private String category;
private String loyalty;
private List<Specialization> specializations;
private Contacts contacts;
Organization model has following parameters:
#PrimaryKey
private OrganizationId organizationId;
private String organizationName;
private String key;
// private Address address;
private String address;
private String phoneNumber;
Filling values like this:
Organization organization = realm.createObject(Organization.class); // Create a new object
OrganizationId organizationId = realm.createObject(OrganizationId.class);
organizationId.setAggregateId("1");
organization.setOrganizationId(organizationId);
organization.setOrganizationName("1-я Клиника Ташкентской Медицинской Академии");
organization.setAddress("Адрес: г. Ташкент, ул. Фароби, 2");
organization.setPhoneNumber("Тел.: (+99871) 214-51-01, 214-50-86, 214-50-43");
organization.setKey(organization.getOrganizationName().toLowerCase());
Doctor doctor = realm.createObject(Doctor.class);
//FULL NAME
FullName fullName = realm.createObject(FullName.class);
fullName.setFirstName("Joe");
fullName.setLastName("Richard");
fullName.setMiddleName("Brown");
doctor.setFullName(fullName);
//CONTACTS
Contacts contacts = realm.createObject(Contacts.class);
String[] phoneNumbers = {"+998903735173"};
contacts.setPhoneNumbers(phoneNumbers);
doctor.setContacts(contacts);
//ORGANIZATION
doctor.setOrganization(organization);
For example, this code returns all doctors with A category:
RealmQuery<Doctor> query = realm.where(Doctor.class);
RealmResults<Doctor> rDoctors = query.contains("category", "A").findAll();
return rDoctors;
My app logic like this: first of all, I open list of organizations. When User clicks on one organization. This will open list of doctors.
So my question is can I find doctors by its sub object(Organization)? Something like this
RealmQuery<Doctor> query = realm.where(Doctor.class);
RealmResults<Doctor> rDoctors = query.someMagicalMethod("organization", organization1).findAll();
return rDoctors;
PS. Yes, I can get it by going deep into organization. I was wondering does Realm.io makes search by object possible. Anyways I love Realm.io
I think it i possible. You can check it out here: http://realm.io/docs/java/latest/#link-queries
As per your case, you can try my following code:
RealmResults<Doctor> rDoctors = realm.where(Doctor.class)
.equalsTo("organization.organizationId", organizationId)
.findAll();
return rDoctors;
Please let me know if it works for you.

Trying write a query with ORMLite?

I'm trying write a query using ORMLite. I need this query check a id of customer in other entity. How could I do it ?
Entities
#DatabaseTable(tableName = "customer")
public class Customer {
#DatabaseField(generatedId = true)
private Integer id;
#DatabaseField
private String name;
#DatabaseField
private Sale sale;
//gets sets
}
#DatabaseTable(tableName = "sale")
public class Sale{
#DatabaseField(generatedId = true)
private Integer id;
#DatabaseField
private Customer customer;
#DatabaseField
private Integer status;
//gets sets
}
Query
Customer customer = new Customer();
customer.setId(1);
customer.setName("Fernando Paiva");
QueryBuilder<Sale, Integer> qb = saleDAO.queryBuilder();
Where where = qb.where();
where.eq("sale.customer.id", customer.getId());
where.and();
where.eq("sale.status", 1);
PreparedQuery<Sale> pq = qb.prepare();
List<Sale> list = saleDAO.query(pq);
Log.i("SALE LIST->", list.size() + "");
You need to use JOIN
Here your example using Join:
First of all, you need a QueryBuilder to each Dao.
You can apply your filter to each QueryBuilder separately
Last but not least, you join the main QueryBuilder (Sales) with the Customer's QueryBuilder and
perform the query.
Here the code
Dao<Sale, Integer> saleDao = DaoManager.createDao(getConnectionSource(), Sale.class);
Dao<Customer, Integer> customerDao = DaoManager.createDao(getConnectionSource(), Customer.class);
QueryBuilder<Sale, Integer> saleQa= saleDao.queryBuilder();
saleQa.where().eq("status", 1);
QueryBuilder<Customer, Integer> customerQa = customerDao.queryBuilder();
customerQa.where().idEq(customer.getId());
sales = saleQa.join(customerQa).query();
Are you trying to use OrmLite to check if the customer id is the same as the sale id and get all of the matching result? If so the below code will do that
qb.where().eq("id", customer.id);
List<Sale> results = saleDAO.query(qb.prepare());
Update:
After rereading your question I realized what you're trying to do
qb.where().in(Sale.customer, id);
See this question for further details.
Ormlite Foreign Entity Searching

Foreignfield no value Ormlite

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.

ORMLite - Query foreign field

Using ORMLite for Android, I need to build a query that returns orders by order id or by customer name. Please consider the following class declarations:
#DatabaseTable(tableName = "order")
public class Order {
#DatabaseField(generatedId = true)
private Long id;
#DatabaseField(foreign = true, canBeNull = false, foreignAutoRefresh = true, columnName = "customer_id")
private Customer customer;
// default constructor, getters and setters...
}
#DatabaseTable(tableName = "customer")
public class Customer {
#DatabaseField(generatedId = true)
private Long id;
#DatabaseField
private String name;
// default constructor, getters and setters...
}
The raw SQL I'm looking for would be something like this:
SELECT
o.*
FROM
order o
JOIN customer c on
o.customer_id = c.id
WHERE
(o.id = ?) OR (c.name = ?)
What is the best way to do this using ORMLite?
ORMLite now supports simple join queries.
So your query would look something like:
QueryBuilder<Customer, Integer> customerQb = customerDao.queryBuilder();
SelectArg nameSelectArg = new SelectArg();
// this gives the c.name = ?
customerQb.where().eq("name", nameSelectArg);
QueryBuilder<Account, Integer> orderQb = orderDao.queryBuilder();
SelectArg idSelectArg = new SelectArg();
// this gives the o.id = ?
orderQb.where().eq("id", idSelectArg);
orderQb.join(customerQb);
// then you set the args and run the query
nameSelectArg.setValue("jim");
idSelectArg.setValue(1);
List<Order> results = orderQb.join(customerQb).query();
No, JOINs are supported in ORMLite https://stackoverflow.com/a/7320091/323128
However, this reference will give a vision how to complete your task

Categories

Resources