Improving Android ORMLite foreign key mapping , based on new version 5.0

简介: Improving Android ORMLite foreign key mapping , based on new version 5.
Improving Android ORMLite foreign key mapping , based on new version 5.0


AClass.java:

import com.j256.ormlite.dao.ForeignCollection;
import com.j256.ormlite.field.DataType;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.field.ForeignCollectionField;
import com.j256.ormlite.table.DatabaseTable;

@DatabaseTable(tableName = "classes")
public class AClass {

    @DatabaseField(generatedId = true)
    public int id;

    @DatabaseField(canBeNull = false, dataType = DataType.INTEGER)
    public int classId;

    @DatabaseField(canBeNull = false, defaultValue = "class", dataType = DataType.STRING)
    public String name;

    @ForeignCollectionField(eager = false)
    public ForeignCollection<Student> students;

    @Override
    public String toString() {
        return "id:" + id + ",classId:" + classId + ",name:" + name;
    }
}



Student.java:

import com.j256.ormlite.field.DataType;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

@DatabaseTable(tableName = "students")
public class Student {
    @DatabaseField(generatedId = true)
    public int id;

    @DatabaseField(canBeNull = false, dataType = DataType.INTEGER)
    public int studentId;

    @DatabaseField(canBeNull = false, dataType = DataType.STRING)
    public String name;

    @DatabaseField(canBeNull = false, foreign = true, foreignAutoRefresh = true)
    public AClass aclass;

    @Override
    public String toString() {
        return "id:" + id + ",studentId:" + studentId + ",name:" + name + ",className:" + aclass.name;
    }
}


ORMLiteDatabaseHelper.java:

import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

public class ORMLiteDatabaseHelper extends OrmLiteSqliteOpenHelper {

    private static ORMLiteDatabaseHelper mDatabaseHelper = null;

    private Dao<AClass, Integer> mClassDao = null;
    private Dao<Student, Integer> mStudentDao = null;

    private final static String DB_NAME = "school.db";
    private final static int DB_VERSION = 1;

    public ORMLiteDatabaseHelper(Context context, String databaseName, CursorFactory factory, int databaseVersion) {
        super(context, DB_NAME, factory, DB_VERSION);
    }

    public static ORMLiteDatabaseHelper getInstance(Context context) {
        if (mDatabaseHelper == null) {
            mDatabaseHelper = new ORMLiteDatabaseHelper(context, DB_NAME, null, DB_VERSION);
        }

        return mDatabaseHelper;
    }

    @Override
    public void onCreate(SQLiteDatabase arg0, ConnectionSource connectionSource) {
        Log.d(this.getClass().getName(), "ORMLite数据库:onCreate");

        try {
            TableUtils.createTableIfNotExists(connectionSource, AClass.class);
            TableUtils.createTableIfNotExists(connectionSource, Student.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        Log.i(this.getClass().getName(), "数据库 -> onUpgrade");

        try {
            // 删除旧的数据库表。
            TableUtils.dropTable(connectionSource, AClass.class, true);
            TableUtils.dropTable(connectionSource, Student.class, true);

            // 重新创建新版的数据库。
            onCreate(database, connectionSource);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public Dao<Student, Integer> getStudentDao() {
        if (mStudentDao == null) {
            try {
                mStudentDao = getDao(Student.class);
            } catch (java.sql.SQLException e) {
                e.printStackTrace();
            }
        }

        return mStudentDao;
    }

    public Dao<AClass, Integer> getClassDao() {
        if (mClassDao == null) {
            try {
                mClassDao = getDao(AClass.class);
            } catch (java.sql.SQLException e) {
                e.printStackTrace();
            }
        }

        return mClassDao;
    }

    @Override
    public void close() {
        super.close();
        mClassDao = null;
        mStudentDao = null;
    }
}



MainActivity.java:

import java.sql.SQLException;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.ForeignCollection;

import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    private Dao<AClass, Integer> mClassDao;
    private Dao<Student, Integer> mStudentDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ORMLiteDatabaseHelper mORMLiteDatabaseHelper = ORMLiteDatabaseHelper.getInstance(getApplicationContext());

        mClassDao = mORMLiteDatabaseHelper.getClassDao();
        mStudentDao = mORMLiteDatabaseHelper.getStudentDao();

        // 在数据库中存储5个班级。
        for (int i = 1; i < 6; i++) {
            AClass aclass = new AClass();
            aclass.classId = i;
            aclass.name = i + "班";
            try {
                mClassDao.createIfNotExists(aclass);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        // 找到id=1的1班。
        AClass class1 = null;
        try {
            class1 = mClassDao.queryForId(1);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // 创建10个学生,这10个学生都归属到1班。
        for (int i = 0; i < 10; i++) {
            Student s = new Student();
            s.studentId = i;
            s.name = "学生" + i;

            // 将新创建的这些学生所在班级指针指向1班。
            // 1班有这19个学生,换言之,这19个学生是1班的学生。
            s.aclass = class1;

            try {
                mStudentDao.createIfNotExists(s);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        ForeignCollection<Student> students = class1.students;
        for (Student s : students) {
            Log.d("数据库", s.toString());
        }
    }
}

相关文章
|
2月前
|
Android开发 Kotlin
The Android Gradle plugin supports only Kotlin Gradle plugin version 1.3.10 and higher
The Android Gradle plugin supports only Kotlin Gradle plugin version 1.3.10 and higher
38 3
|
4月前
|
Android开发
Android studio 出现Plugin [id: ‘com.android.application‘, version: ‘8.1.0‘, apply: false] 问题解决办法
Android studio 出现Plugin [id: ‘com.android.application‘, version: ‘8.1.0‘, apply: false] 问题解决办法
693 1
|
Android开发
Unrecognized Android Studio (or Android Support plugin for IntelliJ IDEA) version ‘202.7660.26.42.74
Unrecognized Android Studio (or Android Support plugin for IntelliJ IDEA) version ‘202.7660.26.42.74
314 0
Unrecognized Android Studio (or Android Support plugin for IntelliJ IDEA) version ‘202.7660.26.42.74
|
安全 Android开发
ERROR: This version of Android Studio cannot open this project, please retry with Android Studio 3.
ERROR: This version of Android Studio cannot open this project, please retry with Android Studio 3.
343 0
ERROR: This version of Android Studio cannot open this project, please retry with Android Studio 3.
|
Linux 编译器 Android开发
【Android 逆向】Android 系统文件分析 ( /proc/ 目录文件分析 | 记录系统和进程信息 | version 内核版本信息文件 )
【Android 逆向】Android 系统文件分析 ( /proc/ 目录文件分析 | 记录系统和进程信息 | version 内核版本信息文件 )
256 0
【Android 逆向】Android 系统文件分析 ( /proc/ 目录文件分析 | 记录系统和进程信息 | version 内核版本信息文件 )
|
Java Android开发
【错误记录】Android Studio 编译报错 ( Could not determine java version from ‘11.0.8‘. | Android Studio 降级 )
【错误记录】Android Studio 编译报错 ( Could not determine java version from ‘11.0.8‘. | Android Studio 降级 )
474 0
【错误记录】Android Studio 编译报错 ( Could not determine java version from ‘11.0.8‘. | Android Studio 降级 )
|
Java Android开发
【错误记录】Android Studio 编译报错 ( Could not determine java version from ‘11.0.8‘. | 仅做参考 | 没有解决实际问题 )
【错误记录】Android Studio 编译报错 ( Could not determine java version from ‘11.0.8‘. | 仅做参考 | 没有解决实际问题 )
380 0
【错误记录】Android Studio 编译报错 ( Could not determine java version from ‘11.0.8‘. | 仅做参考 | 没有解决实际问题 )
|
Android开发
【错误记录】Android Studio 编译报错 ( cannot open this project, please retry with version 4.2 or newer. )
【错误记录】Android Studio 编译报错 ( cannot open this project, please retry with version 4.2 or newer. )
345 0
【错误记录】Android Studio 编译报错 ( cannot open this project, please retry with version 4.2 or newer. )
|
Java 开发工具 Android开发
【错误记录】Android NDK 错误排查记录 ( Could not get version from cmake.dir path ‘xxx\cmake\3.6.4111459‘. )
【错误记录】Android NDK 错误排查记录 ( Could not get version from cmake.dir path ‘xxx\cmake\3.6.4111459‘. )
402 0
【错误记录】Android NDK 错误排查记录 ( Could not get version from cmake.dir path ‘xxx\cmake\3.6.4111459‘. )
|
Android开发
Android dependency 'com.android.support:support-v4' has different version for the compile (26.1.0...
在项目中加入react-native-camera的时候 出现的错误. 解决方案: 修改 implementation project(':react-native-camera') 为 implementation (project(':react-native-camera')) { exclude group: "com.
1793 0
下一篇
无影云桌面