How to implement relationships in Greendao?

2.1k Views Asked by At

I am new to Greendao.I am writing a generator for generating entities in greendao.So,I have two entities Hospital and patient. They have a one to many relationship between them. So,a hospital can have many patients but one patient can have only one hospital. Now Property hospitalId = patient.addLongProperty("hospitalId").getProperty(); this adds a hospitalid column to patient table. and

ToMany hospitalToPatients = hospital.addToMany(patient, hospitalId);

This line creates a one to many relationship between hospital and patient.So what is the use of the lines patient.addToOne(hospital, hospitalId); and hospitalToPatients.setName("patients"); How to implement one to one,one to many,many to one and many to many relationships in greendao ? PS: I copied this code from http://www.vertabelo.com/blog/technical-articles/a-comparison-of-android-orms

 public class ProjectGenerator {

        public static void main(String[] args) throws Exception {
            Schema schema = new Schema(1, "com.example.project");

            // hospital table
            Entity hospital = schema.addEntity("Hospital");
            hospital.addIdProperty();
            hospital.addStringProperty("name");

            // patient table
            Entity patient = schema.addEntity("Patient");
            patient.addIdProperty();
            patient.addStringProperty("name");
            Property hospitalId = patient.addLongProperty("hospitalId").getProperty();

            // patient has a one assigned hospital
            patient.addToOne(hospital, hospitalId);

            // hospital has many patients
            ToMany hospitalToPatients = hospital.addToMany(patient, hospitalId);
            hospitalToPatients.setName("patients");

            // trigger generation with path to the Android project
            new DaoGenerator().generateAll(schema, "../project/src/main/java");
        }
    }
1

There are 1 best solutions below

12
On

So what is the use of the lines patient.addToOne(hospital, hospitalId)

This line is creating a oneToOne relation between hospital and patient .

hospitalToPatients.setName("patients")   

This is just setting the name of foreign key .

As you can see, you have already implemented implement one to one,one to many relationship in your example . patient.addToOne is an example of OneToOne relationships . hospital.addToMany is an example of OneToMany relationships . And greenDao doesn't support ManyToMany relationship directly for more details you can read this .