DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • From Naked Objects to Naked Functions
  • SQLiteOpenHelper and Database Inspector in Android
  • 5 Most Preferred React Native Databases
  • Java Vs. Kotlin: Which One Will Be the Best in 2019?

Trending

  • Developers Beware: Slopsquatting and Vibe Coding Can Increase Risk of AI-Powered Attacks
  • What Is Plagiarism? How to Avoid It and Cite Sources
  • Operational Principles, Architecture, Benefits, and Limitations of Artificial Intelligence Large Language Models
  • How To Build Resilient Microservices Using Circuit Breakers and Retries: A Developer’s Guide To Surviving
  1. DZone
  2. Data Engineering
  3. Databases
  4. A Quick Guide to Using Popular ORM for Android Development

A Quick Guide to Using Popular ORM for Android Development

Object-relational mapping converts data between type systems that are unable to coexist within relational databases and OOP languages.

By 
Kaushal Shah user avatar
Kaushal Shah
·
Updated May. 30, 17 · Opinion
Likes (10)
Comment
Save
Tweet
Share
15.3K Views

Join the DZone community and get the full member experience.

Join For Free

When developing an Android application, developers require a database to store the app data. Though there are various database solutions such as a cloud service or an embedded SQLite database, the best one of all is an ORM.

What Is ORM?

As defined by Techopedia: “Object-relational mapping (ORM) is a programming technique in which a metadata descriptor is used to connect object code to a relational database. Object code is written in object-oriented programming (OOP) languages such as Java or C#. ORM converts data between type systems that are unable to coexist within relational databases and OOP languages.”

Image title

ORMs make a developer's life easy. It allows them to avoid the struggle of developing queries by concatenating strings or handling the connections with database manually. Even typos aren’t a major threat to the queries. The security can be managed without worrying about the resistance to injecting attacks. This means a developer can focus on application functionalities while allowing the database to perform its job.

However, there are many ORMs available out there. We have highlighted the most popular ones below.

Sugar ORM

Built specifically for Android development, Sugar ORM features an API that is easy to learn and remember. It creates the tables on its own and provides a simple method to create one-to-one and one-to-many relationships. It further simplifies CRUD (Create, Read, Update and Delete) with just three functions - save(), delete(), and find() (or findById()).

For adding Sugar ORM to your Android project, you can use Gradle, Maven, or a JAR. Change the name of the application in AndroidManifest.xml and add the following metadata tags to set the name and version of database, enable logging of queries, or create tables by specifying the package name with entity classes.

<application android:label="@string/app_name" android:icon="@drawable/icon"
android:name="com.orm.SugarApp">
...
<meta-data android:name="DATABASE" android:value="hospital.db" />
<meta-data android:name="VERSION" android:value="1" />
<meta-data android:name="QUERY_LOG" android:value="true" />
<meta-data android:name="DOMAIN_PACKAGE_NAME" android:value="pl.epoint.mobiorm.project" />
...
</application>

Now, you can use Sugar ORM by manually creating the entity classes. Note that you do not have to set any annotations as Sugar ORM does this automatically by extending the class.

public class Patient extends SugarRecord {

    private String name
    private Hospital hospital;

    public Patient() {
        // Sugar ORM needs a no-arg constructor
    }

    // getters, setters and other constructors
}

public class Hospital extends SugarRecord {

    private String name

    public Hospital() {}

    // getters, setters and other constructors
}

Now, you can directly access Sugar ORM by using entity objects and query builder.

greenDAO

greenDAO requires no initial configuration when adding it to your application. You only need to use Maven or Gradle for using greenDAO ORM. If you do not use Maven or Gradle, then download greendao and greendao-generator JARs from Maven Central and add it as a library.

greenDAO itself generates classes for your project. However, it doesn’t require to create an additional Java project which gives you information about your database model and additionally, triggers class generation. Take a look at the example below:

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");
    }
}

The class generation should resemble the snippet shown below. Notice that there’s a patient field added to the Hospital class by the greenDAO generator.

// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit. 
/**
 * Entity mapped to table "PATIENT".
 */
public class Patient {

    private Long id;
    private String name
    private Long hospitalId;

    ...

    private Hospital hospital;

    ...
}

// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit. 
/**
 * Entity mapped to table "HOSPITAL".
 */
public class Hospital {

    private Long id;
    private String name;

    ...

    private List<Patient> patients;

    ...
}

Just like its name, greenDAO uses DAOs to connect with a database. You can access DAOs as shown below:

DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "hospital-db", null);
SQLiteDatabase db = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(db);
DaoSession daoSession = daoMaster.newSession();

HospitalDao hospitalDao = daoMaster.getHospitalDao();
PatientDao patientDao = daoMaster.getPatientDao();

However, you don’t need to write this code for each database operation. You can rather store the corresponding DAOs objects in Activity Classes or Applications.

There are many other popular ORMs like ORMLite, ActiveAndroid, Vertabelo Mobile ORM, and more. All of these ORMs help you make your jobs a bit easier. Which ORM would you prefer for your Android development project? Let us know in the comments below.

Database Relational database Android (robot) mobile app Object-oriented programming

Opinions expressed by DZone contributors are their own.

Related

  • From Naked Objects to Naked Functions
  • SQLiteOpenHelper and Database Inspector in Android
  • 5 Most Preferred React Native Databases
  • Java Vs. Kotlin: Which One Will Be the Best in 2019?

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!