Implementation of android Sqlite Orm

Preface

I have always wanted to sort out the usage of database operation. Turning to GreenDao, which is now quite popular, the encapsulated CRUD grammar can not be seen. Of course, it is not that GreenDao is not good, at least not good for beginners. Learning should be gradual and know why it is good. This article refers to a God blog, together with their own understanding and collation, belongs to the earlier database operation mode. Hope to be helpful to beginners

Add database visualization plug-in debug_db for easy viewing.

1. What is ORM

Object Relational Mapping (ORM, or O/RM, or O/R mapping) is a programming technology used to transform data between different types of systems in an object-oriented programming language. In effect, it actually creates a "virtual object database" that can be used in programming languages. Simply understood as a simple mapping relationship between objects and database table fields

2. Download android ORMLite Jar

http://ormlite.com/releases/

Operating on the basis of these two editions

3. Configuring Bean Classes

Use different annotations to label table attributes (field name, field type, primary key, foreign key, etc.)

@DatabaseTable(tableName = "tb_article")
public class Article
{
    @DatabaseField(generatedId = true)
    private int id;
    @DatabaseField
    private String title;
    @DatabaseField(canBeNull = true, foreign = true, columnName = "user_id", foreignAutoRefresh = true)
    private User user;

    public int getId()
    {
        return id;
    }

    public void setId(int id)
    {
        this.id = id;
    }

    public String getTitle()
    {
        return title;
    }

    public void setTitle(String title)
    {
        this.title = title;
    }

    public User getUser()
    {
        return user;
    }

    public void setUser(User user)
    {
        this.user = user;
    }

    @Override
    public String toString()
    {
        return "Article [id=" + id + ", title=" + title + ", user=" + user
                + "]";
    }

}

4. Writing DAO classes

dao corresponds to Bean in general. dao is the encapsulation of specific table operations, while Bean is the mapping of tables.

package dragger2.nuoyuan.com.myapplication.db;

import android.content.Context;

import com.j256.ormlite.dao.Dao;

import java.sql.SQLException;
import java.util.List;

import dragger2.nuoyuan.com.myapplication.bean.Student;

public class StudentDao {

    private Context context;
    private Dao<Student, Integer> userDaoOpe;
    private DatabaseHelper helper;

    public StudentDao(Context context) {
        this.context = context;
        try {
            helper = DatabaseHelper.getHelper(context);
            userDaoOpe = helper.getDao(Student.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * Add a user
     *
     * @param student
     * @throws SQLException
     */
    public void add(Student student) {
        try {
            userDaoOpe.create(student);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public Student get(int id) {
        try {
            return userDaoOpe.queryForId(id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<Student> queryAll() {
        try {
            return userDaoOpe.queryForAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

}

The bottom Api SQLiteOpenHelper provided by Sqlite is used for database operation. OrmLiteSqliteOpenHelper has been encapsulated twice on the basis of SQLiteOpenHelper. We directly inherit the OrmLiteSqliteOpenHelper class to implement onCreate (SQLiteDatabase, Connection Source Connection Source)
And onUpgrade (SQLiteDatabase, Connection Source Connection Source, int oldVersion, int newVersion) for database operations and database upgrade operations
Then we use a singleton to publish a method of creating an instance, getHelper is used to get an OpenHelper instance of our operating database.

5. Testing

Because the test uses Context environment, it is not possible to test with unit tests in Android Studo. It is recommended to test in Eclipse and configure the test environment in Eclipse.

package dragger2.nuoyuan.com.myapplication;


import com.j256.ormlite.dao.Dao;

import java.sql.SQLException;
import java.util.List;

import dragger2.nuoyuan.com.myapplication.bean.Article;
import dragger2.nuoyuan.com.myapplication.bean.Student;
import dragger2.nuoyuan.com.myapplication.bean.User;
import dragger2.nuoyuan.com.myapplication.db.ArticleDao;
import dragger2.nuoyuan.com.myapplication.db.DatabaseHelper;
import dragger2.nuoyuan.com.myapplication.db.StudentDao;
import dragger2.nuoyuan.com.myapplication.db.UserDao;
import dragger2.nuoyuan.com.myapplication.utils.L;


public class TestUtils {

    public void testAddArticle() {
        User u = new User();
        u.setName("000");
        new UserDao(MyApp.context).add(u);
        Article article = new Article();
        article.setTitle("hello world");
        article.setUser(u);
        new ArticleDao(MyApp.context).add(article);

    }

    public void testGetArticleById() {
        Article article = new ArticleDao(MyApp.context).get(1);
        L.e(article.getUser() + " , " + article.getTitle());
    }

    public void testGetArticleWithUser() {
        Article article = new ArticleDao(MyApp.context).getArticleWithUser(1);
        L.e(article.getUser() + " , " + article.getTitle());
    }

    public void testListArticlesByUserId() {
        List<Article> articles = new ArticleDao(MyApp.context).listByUserId(1);
        L.e(articles.toString());
    }

    public void testGetUserById() {
        User user = new UserDao(MyApp.context).get(1);
        L.e(user.getName());
        if (user.getArticles() != null)
            for (Article article : user.getArticles()) {
                L.e(article.toString());
            }
    }

    public void testAddStudent() throws SQLException {
        Dao dao = DatabaseHelper.getHelper(MyApp.context).getDao(Student.class);
        Student student = new Student();
        student.setDao(dao);
        student.setName("Yang Weichao");
        student.create();
    }

    public String querystudentDao() throws SQLException {
        Student user = new StudentDao(MyApp.context).get(1);
        return user.toString();
    }


}

View the effect

Note: ORMLite also provides some base classes, such as ORMLiteBaseActivity, ORMLiteBaseService, which are convenient for database operation. It is not considered here. After all, it is very likely that the project itself needs to inherit its own BaseAction and so on.

Simple use of this, the following will be read generic definition, has been encapsulated in a small disassembly, in an effort to restore the smallest piece of knowledge

Source download: http://pan.baidu.com/s/1geRTRBt

Quote
Introduction to Orm http://blog.csdn.net/lmj623565791/article/details/39121377

Keywords: Database Java Programming Android

Added by jasonc on Wed, 10 Jul 2019 01:35:04 +0300