Android ORMLite的使用

原创 2016年08月31日 16:31:02

环境配置:

下载jar包地址:http://ormlite.com/releases/   下载最新的ormlite-android.jar和ormlite-core.jar

把jar包放在libs文件目录下,然后去build.gradle文件下添加jar包,例如:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile files('libs/ormlite-android-5.0.jar')
    compile files('libs/ormlite-core-5.0.jar')
}

代码:

这里尝试的例子是,一个计划表,一个计划项表,计划表的id是计划项表的外键。

共通的DatabaseHelper.java

这里需要继承OrmLiteSqliteOpenHelper,而不是SQLiteOpenHelper

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
    /**
     * TAG.
     */
    private static final String TAG = "DatabaseHelper";
    /**
     * 数据库名
     */
    public static final String APP_DATABASE_NAME = "healthyapp_db";
    /**
     * 计数器
     */
    private AtomicInteger mOpenCounter = new AtomicInteger();
    /**
     * 版本号
     */
    private static final int DATABASE_VERSION = 1;
    /**
     * datebase helper
     */
    private static DatabaseHelper mDatabaseHelper;
    /**
     * DB
     */
    private SQLiteDatabase mDatabase;
    /**
     * context
     */
    Context context = null;
    /**
     * 所有的dao
     */
    private Map<String, Dao> daos = new HashMap<String, Dao>();

    private DatabaseHelper(Context context) {
        super(context, APP_DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    public static synchronized DatabaseHelper getInstance(Context context) {
        if (mDatabaseHelper == null) {
            mDatabaseHelper = new DatabaseHelper(context.getApplicationContext());
        }
        return mDatabaseHelper;
    }

    /**
     * 获取db文件
     *
     * @param context
     * @return
     */
    public static File getDatabaseFile(Context context) {
        return context.getDatabasePath(APP_DATABASE_NAME);
    }

    // 计数器递增,如果计数为1,则打开一个新的数据库连接,否则,数据库连接已经存在
    public synchronized SQLiteDatabase openDatabase() {
        if (mOpenCounter.incrementAndGet() == 1) {
            mDatabase = mDatabaseHelper.getWritableDatabase();
        }
        return mDatabase;
    }

    // 计数器递减,直到计数为0,则关闭数据库连接
    public synchronized void closeDatabase() {
        if (mOpenCounter.decrementAndGet() == 0 && mDatabase != null) {
            mDatabase.close();
        }
    }

    /**
     * 创建表
     *
     * @param sqLiteDatabase
     * @param connectionSource
     */
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, SchedulePlanEntity.class);
            TableUtils.createTable(connectionSource, SchedulePlanItemEntity.class);
        } catch (java.sql.SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 当数据库需要升级时,会调用这个方法。应该使用这个方法来实现删除表、添加表或者做一些需要升级新的策略版本的事情。
     *
     * @param sqLiteDatabase
     * @param connectionSource
     * @param oldVersion
     * @param newVersion
     */
    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        Log.i(TAG, "onUpgrade oldVersion=" + oldVersion + ", newVersion=" + newVersion);
        try {
            TableUtils.dropTable(connectionSource, SchedulePlanEntity.class, true);
            TableUtils.dropTable(connectionSource, SchedulePlanItemEntity.class, true);
            onCreate(sqLiteDatabase, connectionSource);
        } catch (java.sql.SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取Dao
     *
     * @return
     * @throws SQLException
     */
    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;
        }
    }
}

SchedulePlanEntity.java

@DatabaseTable(tableName = "tb_SchedulePlan")
public class SchedulePlanEntity {
    // planId为主键且自动生成
    @DatabaseField(generatedId = true)
    private int planId;

    @DatabaseField(canBeNull = true, columnName = "user_id")
    private String userId;

    @DatabaseField(canBeNull = true, columnName = "plan_name")
    private String planName;

    @DatabaseField(canBeNull = true, columnName = "selectf")
    private boolean isSelect;

    @DatabaseField(canBeNull = true, columnName = "repeat_time")
    private int repeatTime;

    // queryById时可以直接获取与当前ScheudlePlan相关联的所有planItems
    @ForeignCollectionField(eager = true)
    private ForeignCollection<SchedulePlanItemEntity> planItemList;

    public int getPlanId() {
        return planId;
    }

    public void setPlanId(int planId) {
        this.planId = planId;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getPlanName() {
        return planName;
    }

    public void setPlanName(String planName) {
        this.planName = planName;
    }

    public boolean isSelect() {
        return isSelect;
    }

    public void setSelect(boolean select) {
        isSelect = select;
    }

    public int getRepeatTime() {
        return repeatTime;
    }

    public void setRepeatTime(int repeatTime) {
        this.repeatTime = repeatTime;
    }

    public ForeignCollection<SchedulePlanItemEntity> getPlanItemList() {
        return planItemList;
    }

    public void setPlanItemList(ForeignCollection<SchedulePlanItemEntity> planItemList) {
        this.planItemList = planItemList;
    }

    public String toString() {
        return "plan id: " + planId + " user id: " + userId + " plan name: " + planName
                + " select :" + isSelect + " repeat time: " + repeatTime + "\n";
    }
}
canBeNull属性指定是否该列可以为空,columName属性指定列名

eager设置为true这个集查询会立即执行存放在集合中,如果设置为false,也就是lazy模式需要使用iterator查询?

列表必须是ForeignCollection


SchdulePlanItemEntity.kava

@DatabaseTable(tableName = "tb_SchedulePlanItem")
public class SchedulePlanItemEntity {
    private final static String PLAN_ITEM_NAME_FILED_NAME = "plan_item_name";
    private final static String PLAN_ID_FILED_NAME = "plan_id";

    @DatabaseField(generatedId = true)
    private int planItemId;
    @DatabaseField(canBeNull = true, columnName = PLAN_ITEM_NAME_FILED_NAME)
    private String planItemName;
    // 添加foreignAutoRefresh =true,当调用queryForId时,拿到SchedulePlanItemEntity对象则直接携带了SchedulePlanEntity;
    @DatabaseField(canBeNull = false, foreign = true, columnName = PLAN_ID_FILED_NAME, foreignAutoRefresh = true)
    private SchedulePlanEntity plan;

    public int getPlanItemId() {
        return planItemId;
    }

    public void setPlanItemId(int planItemId) {
        this.planItemId = planItemId;
    }

    public String getPlanItemName() {
        return planItemName;
    }

    public void setPlanItemName(String planItemName) {
        this.planItemName = planItemName;
    }

    public SchedulePlanEntity getPlan() {
        return plan;
    }

    public void setPlan(SchedulePlanEntity plan) {
        this.plan = plan;
    }

    public String toString() {
        return "plan item id: " + planItemId + " plan item name: " + planItemName + " plan name: "
                + plan.getPlanName() + "\n";
    }
}

SchedulePlanDao.java

public class SchedulePlanDao {
    private Context context;
    /**
     * Dao<T,ID>
     */
    private Dao<SchedulePlanEntity, Integer> dao;

    public SchedulePlanDao(Context context) {
        this.context = context;
        try {
            dao = (DatabaseHelper.getInstance(context)).getDao(SchedulePlanEntity.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加
     * 返回的内容是修改的数量
     *
     * @param entity
     */
    public int add(SchedulePlanEntity entity) {
        try {
            return dao.create(entity);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 根据主键删除
     *
     * @param planId
     */
    public int deleteById(int planId) {
        try {
            return dao.deleteById(planId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 获取所有数据
     *
     * @return
     */
    public List<SchedulePlanEntity> queryForAll() {
        try {
            return dao.queryForAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 检索指定内容的所有数据(这里举例是userId)
     *
     * @param userId
     * @return
     */
    public List<SchedulePlanEntity> queryForUserId(String userId) {
        List<SchedulePlanEntity> all = queryForAll();
        List<SchedulePlanEntity> res = new ArrayList<SchedulePlanEntity>();
        for (SchedulePlanEntity entity : all) {
            if (entity.getUserId().equals(userId)) {
                res.add(entity);
            }
        }
        return res;
    }

    public SchedulePlanEntity queryForId(int planId) {
        try {
            return (SchedulePlanEntity) dao.queryForId(planId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 更新数据
     *
     * @param entity
     * @return
     */
    public int update(SchedulePlanEntity entity) {
        try {
            return dao.update(entity);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }
}
查询、更新一定要给主键,否则无效


SchedulePlanItemDao.java

public class SchedulePlanItemDao {
    private Context context;
    /**
     * Dao<T,ID>
     */
    private Dao<SchedulePlanItemEntity, Integer> dao;

    public SchedulePlanItemDao(Context context) {
        this.context = context;
        try {
            dao = (DatabaseHelper.getInstance(context)).getDao(SchedulePlanItemEntity.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加
     * 返回的内容是修改的数量
     *
     * @param entity
     */
    public int add(SchedulePlanItemEntity entity) {
        try {
            return dao.create(entity);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 根据主键删除
     *
     * @param planItemId
     */
    public int deleteById(int planItemId) {
        try {
            return dao.deleteById(planItemId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 获取所有数据
     *
     * @return
     */
    public List<SchedulePlanItemEntity> queryForAll() {
        try {
            return dao.queryForAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过planId获取所有计划项(planId是外键)
     *
     * @param planId
     * @return
     */
    public List<SchedulePlanItemEntity> queryForPlanId(int planId) {
        List<SchedulePlanItemEntity> resList = new ArrayList<SchedulePlanItemEntity>();
        try {
            resList = dao.queryBuilder().where().eq("plan_id", planId).query();
            // 或者直接传入一个带主键的SchedulePlanEntity
            // resList = dao.queryBuilder().where().eq("plan_id", plan).query();
            return resList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return resList;
    }

    public SchedulePlanItemEntity queryForId(int planItemId) {
        try {
            SchedulePlanItemEntity entity = (SchedulePlanItemEntity) dao.queryForId(planItemId);
            return entity;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 更新数据
     *
     * @param entity
     * @return
     */
    public int update(SchedulePlanItemEntity entity) {
        try {
            return dao.update(entity);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }
}


调用,这里举几个例子:

插入计划:

SchedulePlanEntity entity = new SchedulePlanEntity();
entity.setUserId("111");
entity.setPlanName("111");
entity.setSelect(false);
entity.setRepeatTime(1);
dao.add(entity);

删除计划:

dao.deleteById(1)

更新计划:

SchedulePlanEntity entity = new SchedulePlanEntity();
entity.setPlanId(2);
entity.setUserId("112");
entity.setPlanName("112");
entity.setSelect(true);
entity.setRepeatTime(4);
dao.update(entity);

所有属性都要设置,不然会存入null,一定要设置主键

查询所有计划:

List<SchedulePlanEntity> reslList = dao.queryForAll();
查询某个计划并且获取所有计划项:

SchedulePlanEntity entity = dao.queryForId(2);
List<SchedulePlanItemEntity> itemList = new ArrayList<SchedulePlanItemEntity>();
for (SchedulePlanItemEntity item: entity.getPlanItemList()) {
<pre name="code" class="java">    itemList.add(item);
}


查询指定userId的计划:

List<SchedulePlanEntity> reslList = dao.queryForUserId();
查询指定计划项并且获取该计划项对应的计划:

SchedulePlanItemEntity item = dao.queryForId(3);
SchedulePlanEntity plan = item.getPlan();


上述代码其实已经用到了简单的条件查询了:

1、简单的where等于

dao.queryBuilder().where().eq("user_id", userId).query();直接返回SchedulePlanEntity的列表

2、where and 

  1. QueryBuilder<SchedulePlanEntity, Integer> queryBuilder = dao.queryBuilder();  
  2.         Where<SchedulePlanEntity, Integer> where = queryBuilder.where();  
  3.         where.eq("user_id"1);  
  4.         where.and();  
  5.         where.eq("plan_name""xxx");  
  6.   
  7.         //或者  
  8.         dao.queryBuilder().//  
  9.                 where().//  
  10.                 eq("user_id","1").and().//  
  11.                 eq("plan_name""xxx");  

上述两种都相当与:select * from tb_SchedulePlan where user_id = "1" and name = 'xxx' ; 

3、更复杂的查询

  1. where.or(  
  2.                     //  
  3.                     where.and(//  
  4.                             where.eq("user_id","1"), where.eq("plan_name""xxx")),  
  5.                     where.and(//  
  6.                             where.eq("user_id","2"), where.eq("plan_name""yyy")));  

select * from tb_SchedulePlan where ( user_id = "1" and plan_name= 'xxx' )  or ( user_id = "2" and plan_name= 'yyy' )  ;


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

官方软件文档:http://ormlite.com/javadoc/ormlite-core/doc-files/ormlite.html

官网:http://ormlite.com/


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

在Android中使用ORMLite

ORMLite是一款相当容易使用的ORM框架。本文介绍如何在Android中使用ORMLite,开发环境为Android studio。文中还有RecyclerView的用法。

android数据库ormlite的使用

  • 2016-09-20 11:34
  • 20.04MB
  • 下载

android使用orm框架ormlite在控制台打印log日志信息

在默认情况下,在android下默认只打印info级别的日志信息,所以在默认情况只能打印ormlite中创建数据库表的语句,而对于数据的插入和查询等sql语句是不会打印出来的。在ormlite中提供了...

【android】ORMLite框架 的使用方法---给你的数据库操作插上翅膀

一:首先下载 ORMLite Jar 包先去 ORMLite官网下载jar包 写博客时,目前最新的,对于Android为:ormlite-android-5.0.jar 和 ormlite-core-...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)