Ormlite的简单使用详解

package com.example.ormdb;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.example.ormdb.bean.Person;
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;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by Linsa on 2017/7/13.
 */

public class MyDbHelper extends OrmLiteSqliteOpenHelper {

    private static final int DB_VERSION=1;
    private static final String DB_NAME="person.db3";


    /**
     * 用来存放Dao的地图
     */
    private Map daos = new HashMap();

    private static MyDbHelper instance;

    public MyDbHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
        try {
//            TableUtils.createTable(connectionSource,Student.class);
            TableUtils.createTable(connectionSource,Person.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) {

    }

    public synchronized  Dao getDao(Class clazz) throws SQLException {
        Dao dao=null;
        String simpleName = clazz.getSimpleName();
        if (daos.containsKey(simpleName)) {
            dao = daos.get(simpleName);

        }else{
            dao = super.getDao(clazz);
            daos.put(simpleName,dao);
        }
        return dao;
    }


    /**
     * 获取一个数据库的单实例
     * @param context
     * @return
     */
    public MyDbHelper getInstance(Context context){
        context = context.getApplicationContext();
        if (instance==null){
            synchronized (MyDbHelper.class) {
                if (instance==null) {
                    instance = new MyDbHelper(context);
                }
            }
        }
        return instance;
    }


    @Override
    public void close() {
        super.close();
        for (String key:daos.keySet()) {
            Dao dao = daos.get(key);
            dao=null;
        }
    }
}

PersonDao.class文件的详细信息,数据库操作的中间层

package com.example.ormdb.dao;

import android.content.Context;

import com.example.ormdb.MyDbHelper;
import com.example.ormdb.bean.Person;
import com.j256.ormlite.dao.Dao;

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

/**
 * Created by Linsa on 2017/7/13.
 */


public class PersonDao {

    private  Dao mPersonDao;

    public PersonDao(Context context)  {
        try {
            mPersonDao = new MyDbHelper(context).getDao(Person.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 向数据库中添加一条数据
     * @param person
     */
    public void add(Person person){
        try {
            mPersonDao.create(person);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除一条数据
     * @param person
     */
    public void delete(Person person){
        try {
            mPersonDao.delete(person);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    /**
     * 删除一组数据
     */
    public void deleteCollection(ArrayList arrayList){
        try {
            mPersonDao.delete(arrayList);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询一条记录
     * @param id
     * @return
     */
    public Person queryForId(int id) {
        Person person = null;
        try {
            person = (Person) mPersonDao.queryForId(id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return person;
    }


    /**
     * 查询所有记录
     * @return
     */
    public List queryForAll() {
        List themes = new ArrayList();
        try {
      
      themes = mPersonDao.queryForAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return themes;
    }



}

数据Bean的详细代码

package com.example.ormdb.bean;

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

import java.io.Serializable;

/**
 * Created by Linsa on 2017/7/13.
 */

@DatabaseTable
public class Person implements Serializable {

    //这里的这个属性是自增的属性,当设置了这个属性以后,默认也就是认定这个属性为主键,如果再设置 id=true的话,则会进行报错
    //java.lang.IllegalArgumentException: Must specify one of id, generatedId, and generatedIdSequence with id
    @DatabaseField(id =true,generatedId = true)
    public int id;
    @DatabaseField
    public String name;
    @DatabaseField
    public int age;
    @DatabaseField
    public String sex;

    @Override
    public String toString() {
        return "Person{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }
}

MainActivity.java的详细代码

package com.example.ormdb;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.ormdb.bean.Person;
import com.example.ormdb.dao.PersonDao;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    @InjectView(R.id.btn_querry)
    Button btnQuerry;
    @InjectView(R.id.btn_add)
    Button btnAdd;
    @InjectView(R.id.btn_delete)
    Button btnDelete;

    private int i = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);
    }

    @OnClick({R.id.btn_add, R.id.btn_querry, R.id.btn_delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_add:
                Person person = new Person();
                person.name = "onex" + i;
                person.sex = "女";

                new PersonDao(MainActivity.this).add(person);
                i++;
                Toast.makeText(MainActivity.this, "add success", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_querry:
                List persons = new PersonDao(MainActivity.this).queryForAll();
                for (Person p : persons) {
                    Toast.makeText(MainActivity.this, p.toString(), Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.btn_delete:

                //设置删除的时候只要设置对象的一个id就可以
                //设置其他的属性也是可以的

                Person delPer = new Person();
                delPer.id=5;
//                delPer.name="onex3";
//                delPer.sex="女";
                new PersonDao(MainActivity.this).delete(delPer);

                Toast.makeText( MainActivity.this, "delete success!", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        new MyDbHelper(MainActivity.this).close();
    }
}

数据库jar包的下载和使用:
jar包下载地址 :http://ormlite.com/releases/
具体下载如下图所示:

Ormlite的简单使用详解_第1张图片
UOUCCM{6WGZ)TMELJ$JUFPL.png

具体的可以查看官方文档 :http://ormlite.com/javadoc/ormlite-android/

参考范文:http://blog.csdn.net/lmj623565791/article/details/39122981

你可能感兴趣的:(Ormlite的简单使用详解)