android OrmLite,androidormlite

來源:互聯網
上載者:User

android OrmLite,androidormlite

最近在使用ormlite架構進行資料庫的操作,下面簡單的寫個demo來學習下

1.下載jar包

這裡使用的是ormlite-core-5.0.jar 和 ormlite-android-5.0.jar

將下載的jar包放到我們項目的libs檔案夾下

2.建立實體類對象

每一個實體類對應一張表,在我們項目中的bean目錄下建立一個Student類

package com.item.jiejie.lite.db;import com.j256.ormlite.field.DatabaseField;import com.j256.ormlite.table.DatabaseTable;/** * 定義實體類Bean,代表一張表 * 需要持久化到資料庫的類,類名前需要添加@DatabaseTable,產生對應的表 類中的成員需要添加@DatabaseField,產生前面的表中的欄位 * 注意:在需要持久化的類中必須要有無參的構造器 * Created by jiejie on 2017/5/3. */@DatabaseTable(tableName = "tb_hello")public class Hello {    @DatabaseField(generatedId = true)    private int id;    @DatabaseField(columnName = "name")    private String name;    @DatabaseField(columnName = "sex")    private String sex;    @DatabaseField(columnName = "age")    private int age;    /*     * 常用參數     * generatedId = true 主鍵,自動產生的id 該註解下的欄位必須是整形(int long)     * id = true 主鍵     * unique = true 唯一約束 預設false     * columnName = "name" 表欄位名,預設為變數名稱     * canBeNull = false 非空約束,預設為true,可以為null,設為false就不能為null     * foreign = true 外鍵引用,欄位不能是一個原始類型,應該定義一個對象當做外鍵引用,在外鍵對象的類中,必須要有一     * 個ID欄位(ID, generatedId,generatedIdSequence)     * foreignAutoRefersh = true 在使用外鍵引用時,由於ormlite的外鍵引用使用的是對象,所以添加這個欄位的話在查詢,會把     * 外鍵的對象資料都查詢回來,否則外鍵資料就只有那個對象的主鍵有值,其餘的值都是null     * defaultValue = "小明" 預設值     * index = true 建立索引 預設為false     * uniqueIndex = true 唯一索引 預設為false     */    //空的構造方法一定要有,否則資料庫會建立失敗    public  Hello(){    }    public Hello(String name, String sex, int age) {        this.name = name;        this.sex = sex;        this.age = age;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getSex() {        return sex;    }    public void setSex(String sex) {        this.sex = sex;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    @Override    public String toString() {        return "Hello{" +                "name='" + name + '\'' +                ", sex='" + sex + '\'' +                ", age=" + age +                '}';    }}

3.編寫我們的資料helper類

package com.item.jiejie.lite.db;import android.content.Context;import android.database.sqlite.SQLiteDatabase;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;import java.sql.SQLException;/** * 編寫DAO類 * Created by jiejie on 2017/5/3. */public class DataHelper extends OrmLiteSqliteOpenHelper{    private static  final  String TABLE_NAME = "Hellotext.db";    /**     * helloDao 沒張表對應一個     */    private Dao<Hello,Integer> helloDao = null;    /**構造方法*/    public DataHelper(Context context) {        super(context, TABLE_NAME, null, 1);    }    //建立資料表    @Override    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {        try {            TableUtils.createTable(connectionSource,Hello.class);            Log.d("jiejie","資料庫建立成功");        } catch (SQLException e) {            e.printStackTrace();            Log.d("jiejie","資料庫更新成功");        }    }    //資料庫更新    @Override    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) {        try {            TableUtils.dropTable(connectionSource,Hello.class,true);            onCreate(sqLiteDatabase,connectionSource);        } catch (SQLException e) {            e.printStackTrace();        }    }    /**     * 單例擷取該Helper     * 1.先把建構函式私人化     * 2.對外提供一個靜態方法     * 3.在方法中判斷如果已經存在就不再建立,如果不存在再建立這樣就永遠只有一個DataHelper對象     * 4.為了安全執行緒,需要再方法錢提供一個安全執行緒關鍵字synchronized     */    private static  DataHelper instance;    public static  synchronized  DataHelper getHeper(Context context){        if(instance == null){            synchronized (DataHelper.class){                if(instance == null){                    instance = new DataHelper(context);                }            }        }        return instance;    }    public Dao<Hello,Integer> getHelloDao() throws  SQLException{        if(helloDao == null){            helloDao = getDao(Hello.class);        }        return helloDao;    }    public  synchronized void clearData(Class<Hello> clase){        try {            TableUtils.clearTable(connectionSource,clase);        } catch (SQLException e) {            e.printStackTrace();        }    }    /**     * 釋放資源     */    @Override    public void close() {        super.close();        helloDao = null;    }}

4.編寫我們的Dao類的進行增刪改查的操作

package com.item.jiejie.lite.db;import android.content.Context;import com.j256.ormlite.dao.Dao;import com.j256.ormlite.support.DatabaseConnection;import java.sql.SQLException;import java.sql.Savepoint;import java.util.ArrayList;import java.util.List;/** * 定義Data Access Objects,對指定的表進行增刪改查的操作 * Created by jiejie on 2017/5/3. */public class HelloDao {    private Dao<Hello,Integer> helloDao;    private DataHelper dataHelper;    /**     * 構造方法,擷取資料庫協助類執行個體,通過傳入class對象得到相應的Dao     * @param context     */    public HelloDao(Context context){        try {            dataHelper = DataHelper.getHeper(context);            helloDao = dataHelper.getHelloDao();        } catch (SQLException e) {            e.printStackTrace();        }    }    /**     * 添加一條記錄     * @param hello     */    public void add(Hello hello){        try {            helloDao.create(hello);        } catch (SQLException e) {            e.printStackTrace();        }    }    /**     * 插入大量的資料     * 開啟事務     * 關閉自動認可     * @param hellos     */    public void addList(List<Hello> hellos){        try{            DatabaseConnection conn = helloDao.startThreadConnection();            Savepoint savepoint = conn.setSavePoint(null);            helloDao.setAutoCommit(conn,false);            for(Hello hello : hellos){                helloDao.createOrUpdate(hello);            }            conn.commit(savepoint);            helloDao.endThreadConnection(conn);        }catch (SQLException e){            e.printStackTrace();        }    }    /**     * 刪除一條記錄     * @param hello     */    public void delete(Hello hello){        try {            helloDao.delete(hello);        } catch (SQLException e) {            e.printStackTrace();        }    }    /**     * 更新一條記錄     * @param hello     */    public void update(Hello hello){        try {            helloDao.update(hello);        } catch (SQLException e) {            e.printStackTrace();        }    }    /**     * 查詢一條記錄     * @param id     * @return     */    public Hello queryForId(int id){        Hello hello = null;        try {            hello = helloDao.queryForId(id);        } catch (SQLException e) {            e.printStackTrace();        }        return hello;    }    /**     * 查詢所有的記錄     * @return     */    public List<Hello> queryForAll(){        List<Hello> hellos = new ArrayList<>();        try {            hellos = helloDao.queryForAll();        } catch (SQLException e) {            e.printStackTrace();        }        return hellos;    }}

5.測試

我在測試的時候,類比插入3w條資料時,發現不同的模擬器 插入的時間不同,有的9s有的要將近十幾s,

可能我在編寫  插入大資料的時候還是有點問題的

 private class TaskDb extends AsyncTask<Integer,Void,Long>{        @Override        protected void onPreExecute() {            super.onPreExecute();        }        @Override        protected Long doInBackground(Integer... params) {            long start = System.currentTimeMillis();            List<Hello> hList = new ArrayList<Hello>();            for(int i=0;i<10000;i++){                Hello hello = new Hello("Hello" + i,"nan", i);                hList.add(hello);            }            helloDao.addList(hList);            long endTime = System.currentTimeMillis();            return endTime - start;        }        @Override        protected void onPostExecute(Long aLong) {            super.onPostExecute(aLong);            Log.d("jiejie","資料載入成功 " +aLong);            Toast.makeText(MainActivity.this,"資料載入成功用時" +aLong ,Toast.LENGTH_SHORT).show();        }    }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.