Fork me on GitHub

sqlite ORMLite 框架应用

bean

package com.test.deamo.bean;

import android.os.Parcel;
import android.os.Parcelable;

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

/**
 * author: yhf
 * Description:
 * date: 2016/04/20 18:22
 */
@DatabaseTable(tableName = "tb_account")
public class Account implements Parcelable {
    @DatabaseField(generatedId = true)
    private int id;
    @DatabaseField(columnName = "user_name")
    private String userName;// 用户姓名
    @DatabaseField(columnName = "password")
    private String password;//密码
    @DatabaseField(columnName = "token")
    private String token;// token值

    public int getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
    
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(this.id);
        dest.writeString(this.userName);
        dest.writeString(this.password);
        dest.writeString(this.token);
    }

    public Account() {
    }

    protected Account(Parcel in) {
        this.id = in.readInt();
        this.userName = in.readString();
        this.password = in.readString();
        this.token = in.readString();
    }

    public static final Creator<Account> CREATOR = new Creator<Account>() {
        @Override
        public Account createFromParcel(Parcel source) {
            return new Account(source);
        }

        @Override
        public Account[] newArray(int size) {
            return new Account[size];
        }
    };
}
DatabaseHelper
package com.test.deamo.utils.db;

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

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 com.test.deamo.bean.Account;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by administrator
 * Description 数据库操作封装
 * 2016/4/27 9:06.
 */
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

    private static final String TABLE_NAME = "test.db";

    private Map<String, Dao> daos = new HashMap<String, Dao>();

    private DatabaseHelper(Context context)
    {
        super(context, TABLE_NAME, null, 4);
    }

    @Override
    public void onCreate(SQLiteDatabase database,
                         ConnectionSource connectionSource)
    {
        try
        {
            TableUtils.createTable(connectionSource, Account.class);
        } catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase database,
                          ConnectionSource connectionSource, int oldVersion, int newVersion)
    {
        try
        {
            TableUtils.dropTable(connectionSource, Account.class, true);
            onCreate(database, connectionSource);
        } catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

    private static DatabaseHelper instance;

    /**
     * 单例获取该Helper
     *
     * @param context
     * @return
     */
    public static synchronized DatabaseHelper getHelper(Context context)
    {
        context = context.getApplicationContext();
        if (instance == null)
        {
            synchronized (DatabaseHelper.class)
            {
                if (instance == null)
                    instance = new DatabaseHelper(context);
            }
        }

        return instance;
    }

    public synchronized Dao getDao(Class clazz) throws SQLException
    {
        Dao dao = null;
        String className = clazz.getSimpleName();

        if (daos.containsKey(className))
        {
            dao = daos.get(className);
        }
        if (dao == null)
        {
            dao = super.getDao(clazz);
            daos.put(className, dao);
        }
        return dao;
    }

    /**
     * 释放资源
     */
    @Override
    public void close()
    {
        super.close();

        for (String key : daos.keySet())
        {
            Dao dao = daos.get(key);
            dao = null;
        }
    }
}

dao类

package com.test.deamo.dao;

import android.content.Context;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.test.deamo.bean.Account;
import com.test.deamo.utils.db.DatabaseHelper;

import java.sql.SQLException;

public class AccountDao {
    private Context context;
    private Dao<Account, Integer> accountDao;
    private DatabaseHelper databaseHelper;

    public AccountDao(Context context) {
        this.context = context;
        try {
            databaseHelper = DatabaseHelper.getHelper(this.context);
            accountDao = databaseHelper.getDao(Account.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加用户信息
     * @param account
     */
    public void add(Account account){
        try {
            accountDao.create(account);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新用户信息
     * @param account
     */
    public void update(Account account){
        try {
            accountDao.update(account);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据token获取account实体
     * @param token
     * @return Account account
     */
    public Account getAccountWithToken(String token){
        return getAccountWithFiled("token", token);
    }

    /**
     * 根据字段名和值获取账号实体
     * @param fieldName
     * @param fieldVal
     * @return
     */
    public Account getAccountWithFiled(String fieldName, String fieldVal){
        Account account = null;
        try {
            QueryBuilder<Account, Integer> queryBuilder = accountDao.queryBuilder();
            Where<Account, Integer> where = queryBuilder.where();
            where.eq(fieldName, fieldVal);
            account = where.queryForFirst();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return account;
    }
}

 

posted @ 2016-04-30 12:31  秋楓  阅读(933)  评论(0编辑  收藏  举报