realm3.0简单使用

作者: 玉树林枫 | 来源:发表于2017-03-30 23:13 被阅读0次

    前言

    在android开发中,可供选择的数据库很多,如 greenDAORealmormlite-android等很多,其中本人用过的有greenDAO,Realm,在上一篇中介绍了greenDAO 3.2的简单使用,在本文将简单地介绍一下realm

    配置环境

    1. 在(project)项目的 build.gradle 文件中添加如下配置

       buildscript {
            repositories {
            jcenter()
            }
            dependencies {
            classpath "io.realm:realm-gradle-plugin:3.0.0"
            }
        }
    

    2. 在module中的 build.gradle 文件中添加如下配置

      apply plugin: 'realm-android'
    

    使用方法

    1. 初始化数据库,一般在Application中初始化

    /**
     * Realm对象只能在创建它的线程中使用
     */
    private void initRealm() {
        Realm.init(this);
        RealmConfiguration   realmConfiguration = new RealmConfiguration.Builder()
                        .schemaVersion(3)//数据库版本
                        .name("Note.realm")//数据库名称
      //                .migration(migration) 数据库升迁
                .build();
        Realm.setDefaultConfiguration(realmConfiguration);
    }
    

    2. 创建对象,并继承RealmObject

    User类

    public class User extends RealmObject {
    
    @PrimaryKey
    private long id;
    
    @Required //强制不为null,默认为""
    private String name;
    
    //@Ignore
    private int age;
    //@Ignore
    private boolean sex;
    
    @Ignore //不被保存
    private int sessionId;
    
    //@Ignore
    private RealmList<Email> emails;//一对多
    
    public User(long id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
    
    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public boolean isSex() {
        return sex;
    }
    
    public void setSex(boolean sex) {
        this.sex = sex;
    }
    
    public RealmList<Email> getEmails() {
        return emails;
    }
    
    public void setEmails(RealmList<Email> emails) {
        this.emails = emails;
    }
    
    //必须要有默认构造函数
    public User() {
    }
    
    public void setId(long id) {
        this.id = id;
    }
    
    public long getId() {
        return id;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
    
    public int getSessionId() {
        return sessionId;
    }
    
    public void setSessionId(int sessionId) {
        this.sessionId = sessionId;
      }
    }
    

    Email类

    public class Email extends RealmObject {
    
    private String address;
    private boolean active;
    //    @Ignore
    private String type;
    
    public Email(String address, boolean active) {
        this.address = address;
        this.active = active;
    }
    
    public String getType() {
        return type;
    }
    
    public void setType(String type) {
        this.type = type;
    }
    
    public String getAddress() {
        return address;
    }
    
    public void setAddress(String address) {
        this.address = address;
    }
    
    public boolean isActive() {
        return active;
    }
    
    public void setActive(boolean active) {
        this.active = active;
    }
    
    public Email() {
    }
    }
    

    3. 增删改查

    realm = Realm.getDefaultInstance();//获取realm对象
    

    private void insert() {
    //方法一
    //        realm.beginTransaction();
    //        User user = realm.createObject(User.class,1); // Create a new object
    //        user.setName("yuShu");
    //        user.setAge(18);
    //        realm.commitTransaction();
    
    //        //方法二,创建一个非管托的对象,通过realm.copyToRealm(user2)
    //        User user2 = new User(1,"yuShu", 18);
    //        realm.beginTransaction();
    //        realm.copyToRealmOrUpdate(user2);//对象存在则更新,否则插入
    //        realm.commitTransaction();
    
        //方法三:自动处理写入事物的开始和提交,并在错误发生时取消写入事物
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                RealmList<Email> emails = new RealmList<>();
                for (int i = 0; i < 3; i++) {
                    Email email = realm.createObject(Email.class);
                    email.setActive(false);
                    email.setAddress(i + "894295059@qq.com");
                    email.setType("QQ");
                    emails.add(email);
                }
                User user = realm.createObject(User.class, 1);//id不可重复
                user.setName("yuShu");
                user.setAge(28);
                user.setSex(true);
                user.setSessionId(111);
                user.setEmails(emails);//设置一对多关系
                Log.i(TAG, "execute: ");
            }
        });
    }
    

    private void delete() {
        final RealmResults<User> results = realm.where(User.class).findAll();
        // All changes to data must happen in a transaction
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                // remove single match
    //                results.deleteFirstFromRealm(); //删除第一个
    //                results.deleteLastFromRealm(); //删除最后一个
    
                // remove a single object
                User user = results.get(1);
                user.deleteFromRealm();
    
    //                // Delete all matches
    //                results.deleteAllFromRealm(); //删除所有
            }
        });
    }
    

    private User findByEmail() {
        RealmQuery<User> query = realm.where(User.class);
        return query.equalTo("emails.address", "1894295059@qq.com").findFirst();//emails必须是字段
    }
    
    private void update() {
        User user = findByEmail();
        realm.beginTransaction();
        user.setAge(25);
        user.setName("GuYuShu");
        realm.commitTransaction();
    }
    

    private User findByEmail() {
        RealmQuery<User> query = realm.where(User.class);
        return query.equalTo("emails.address", "1894295059@qq.com").findFirst();//emails必须是字段
    }    
    
    private User findById(long id) {
        RealmQuery<User> query = realm.where(User.class);
        // 组合查询
        query.equalTo("id", id)
                .beginGroup()
                .equalTo("name", "yuShu")
                .or()
                .contains("name", "Jo")
                .endGroup();
        User user = query.findFirst();
        return user;
    }
    
    private RealmResults<User> findAll() {
        RealmQuery<User> query = realm.where(User.class);
        return query.findAll();
    }
    

    4. 数据库升迁

    /**
     * Realm对象只能在创建它的线程中使用
     */
    private void initRealm() {
        Realm.init(this);
        realmConfiguration = new RealmConfiguration.Builder()
                .schemaVersion(3)//数据库版本
                .name("Note.realm")//数据库名称
                .migration(migration)//数据库升迁
                .build();
        Realm.setDefaultConfiguration(realmConfiguration);
    }
    
    
    //升级
    RealmMigration migration = new RealmMigration() {
        @Override
        public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
            RealmSchema schema = realm.getSchema();
            if (oldVersion == 0) {
                schema.get("User")
                        .addField("age", int.class)
                        .addRealmListField("emails", schema.get("Email"));
                oldVersion++;
            }
            if (oldVersion == 1) {
                schema.get("User")
                        .addField("sex", boolean.class);
                oldVersion++;
            }
            if (oldVersion == 2) {
                schema.get("Email")
                        .addField("type", String.class);
            }
        }
    };
    

    以上只是介绍了realm的基本使用,更详细的资料可以查看官网

    相关文章

      网友评论

        本文标题:realm3.0简单使用

        本文链接:https://www.haomeiwen.com/subject/kqxmottx.html