android的ORMLite的sqlite自定义框架

本文介绍了如何在Android应用中使用ORMLite框架创建自定义的SQLite数据库解决方案。通过此框架,可以在安装时初始化数据库,并在版本升级时进行更新。通过对象关系映射,实现了对数据库的增删改查操作。实现思路包括DBHelper负责初始化和版本更新,DAO层提供功能接口,而实体类对应数据库表。示例代码包括DBHelper、UserDao、TerminalDao和DeviceDao等类的实现。
摘要由CSDN通过智能技术生成

android的ORMLite的sqlite自定义框架


       android中经常会用到sqlite数据库存储手机本地数据。

      在java后台中,也有类似的对象关系映射数据库框架,

      例如hibernate、mybatis数据库框架


      ORMLite时android中扩展性比较好的一款数据库框架。


      准备工作,导入ORMLite:

    

    compile 'com.j256.ormlite:ormlite-android:5.0'
    compile 'com.j256.ormlite:ormlite-core:5.0'


      自定义sqlite框架实现效果:

      1、 app安装的时候,会初始化数据库

      2、 app版本升级后,可以更新android数据库

      3、 通过javaBean对象、数据库字段的关系的方式实现对数据库的

            增删改查的操作。

    

      实现思路:

      通过应用层调用依次调用底层逻辑层的思路实现。

      1、dbHelp里实现sqlite的初始化和版本更新功能、调用dao的功能

      2、dao层提供不同功能dao的功能与扩展口。

      3、实体类层提供不同的与sqlite数据库对应的实体类与扩展口。


   

      实现思路图:

    


 

      实现代码:

     DBHelper.java:

public class DBHelper extends OrmLiteSqliteOpenHelper {

    private static final String TAG = "DBHelper";

    // 数据库名称
    private static final String DATABASE_NAME = "steward.db";

    // 数据库版本
    // 4---v1.0.9
    // 5:添加synHead到contactbase v1.0.11
    // 6:创建短信签名表 v1.0.15
    // 7:
    private static final int DATABASE_VERSION = 1;

    private Context ctx;

    // 数据库连接
    private AndroidDatabaseConnection connection = null;

    private FamilyDao muser;
    private DeviceDao device;
    private DeviceStateDao state;
    private ModelDao model;
    private ModelInfoDao modelInfo;
    private RoomDao room;
    private TerminalDao terminal;
    private UserDao user;
    private DeviceTerminalChooseDao choose;
    private UserFamilyRelationDao relation;
    private DeviceTerminalRelationDao relations;
    private VoiceSetDao voices;
    private AlarmMessageDao mAlarmMessageDao;
    private ModeVoiceDao mVoices;
    private CombinationVoiceDao mCombination;
    private VideoUserDao vUserDao;
    private AirConditionDaoImpl airCondition;

    private DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        ctx = context;
    }

    public static DBHelper dbHelper;

    public static DBHelper getIntance(Context ctx) {
        if (dbHelper == null) {
            dbHelper = new DBHelper(ctx);
        }
        return dbHelper;
    }



    @Override
    public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
//		LogUtil.i(TAG, "onCreate");
        try {
            // 建表
            TableUtils.createTable(connectionSource, Family.class);
            TableUtils.createTable(connectionSource, DeviceState.class);
            TableUtils.createTable(connectionSource, Device.class);
            TableUtils.createTable(connectionSource, Model.class);
            TableUtils.createTable(connectionSource, ModelInfo.class);
            TableUtils.createTable(connectionSource, Room.class);
            TableUtils.createTable(connectionSource, Terminal.class);
            TableUtils.createTable(connectionSource, User.class);
            TableUtils.createTable(connectionSource, DeviceTerminalChoose.class);
            TableUtils.createTable(connectionSource, UserFamilyRelation.class);
            TableUtils.createTable(connectionSource, DeviceTerminalRelation.class);
            TableUtils.createTable(connectionSource, VoiceSet.class);
            TableUtils.createTable(connectionSource, AlarmMessage.class);
            TableUtils.createTable(connectionSource, ModelVoice.class);
            TableUtils.createTable(connectionSource, CombinationVoice.class);
            TableUtils.createTable(connectionSource, Video.class);
            TableUtils.createTable(connectionSource, AirCondition.class);
            execSQLByBatch(db);
//			TableUtils.createTable(connectionSource, BaseDevice.class);
        } catch (Exception e) {
//			LogUtil.e(TAG, "创建数据库失败");
            throw new RuntimeException(e);
        }
    }

    public static void execSQLByBatch(SQLiteDatabase db) {
        List<String> list = new ArrayList<>();
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('C9', '03')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('C9', '04')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('C9', '05')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('C9', '07')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('C9', '0A')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('C9', '0E')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('C9', '0F')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('CF', '01')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('CF', '08')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('CF', '09')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('CF', '0B')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('CF', '0C')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('CF', '0D')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('CF', '10')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('CF', '03')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('CF', '05')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('CF', '07')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('CF', '0A')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('CF', '0E')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('CF', '0F')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('CF', '06')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('CF', '1C')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('CF', '02')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('CF', '17')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('CF', '13')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('D6', '01')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('D6', '02')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('D6', '10')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('D6', '06')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('D6', '1C')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('D6', '0F')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('D2', '02')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('CC', '06')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('DA', '17')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('D8', '16')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('DB', '1A')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('DC', '1C')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('CF', '1B')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('CF', '11')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('CF', '12')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('CF', '15')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('C9', '15')");
        list.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('CF', '04')");

        try {
            db.beginTransaction();
            for (String sql : list) {
                db.execSQL(sql);
            }
            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.endTransaction();
        }
    }
//		private SQLiteDatabase sqLiteDatabase(SQLiteDatabase db){
//
		List<String> sqls=new ArrayList<>();
		sqls.add("INSERT INTO t_device_terminal_static(f_terminal_type,f_device_type) VALUES('"  + "C9', '03"  +
// "')");
		dic.execSQLByBatch(sqls);
		db.insert("t_device_terminal_static",null,cv);
//		return db;
//	}


    @Override
    public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        //如果版本号不一样,重置数据信息
        clearData();
        execSQLByBatch(db);
//		LogUtil.i(TAG, "onUpgrade")onUpgrade;
//		LogUtil.d(TAG, "oldVersion=" + oldVersion + " newVersion=" + newVersion);
//
//		int upgradeVersion = oldVersion;
//		LogUtil.d(TAG, "1 == " + upgradeVersion);
//		if (1 == upgradeVersion) {
//			try {
//				TableUtils.createTable(connectionSource, LinkageList.class);
//				TableUtils.createTable(connectionSource, Linkage.class);
//				TableUtils.createTable(connectionSource, StateTemp.class);
//				TableUtils.createTable(connectionSource, MessageButton.class);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//			upgradeVersion = 2;
//		}
//		if (2 == upgradeVersion) {
//			try {
//				TableUtils.createTable(connectionSource, StateSlidingWindow.class);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//			upgradeVersion = 3;
//		}
    }

    /**
     * 读取数据库文件(.sql),并执行sql语句
     */
    @SuppressWarnings("unused")
    private void executeSchema(SQLiteDatabase db, String schemaName) {
        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(ctx.getAssets().open("schema/" + schemaName)));
            String line;
            String buffer = "";
            while ((line = in.readLine()) != null) {
                buffer += line;
                if (line.trim().endsWith(";")) {
                    db.execSQL(buffer.replace(";", ""));
                    buffer = "";
                }
            }
        } catch (IOException e) {
            Log.e("db-error", e.toString());
        } finally {
            try {
                if (in != null)
                    in.close();
            } catch (IOException e) {
                Log.e("db-error", e.toString());
            }
        }
    }

    public AndroidDatabaseConnection getConnection() {
        if (connection == null) {
            connection = new AndroidDatabaseConnection(getWritableDatabase(), true);
        }

        return connection;
    }

    public FamilyDao getfamilyTableDao() {
        if (muser == null) {
            try {
                muser = new FamilyDaoImpl(ctx, connectionSource, Family.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return muser;
    }

    public DeviceDao getDeviceTableDao() {
        if (device == null) {
            try {
                device = new DeviceDaoImpl(ctx, connectionSource, Device.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return device;
    }

    public DeviceStateDao getDeviceStateTableDao() {
        if (state == null) {
            try {
                state = new DeviceStateDaoImpl(ctx, connectionSource, DeviceState.class) {
                };
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return state;
    }

    public ModelDao getModelDao() {
        if (model == null) {
            try {
                model = new ModelDaoImpl(ctx, connectionSource, Model.class) {
                };
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return model;
    }

    public ModelInfoDao getModelInfoDao() {
        if (modelInfo == null) {
            try {
                modelInfo = new ModelInfoDaoImpl(ctx, connectionSource, ModelInfo.class) {
                };
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return modelInfo;
    }

    public RoomDao getRoomTableDao() {
        if (room == null) {
            try {
                room = new RoomDaoImpl(ctx, connectionSource, Room.class) {
                };
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return room;
    }

    public TerminalDao getTerminalTableDao() {
        if (terminal == null) {
            try {
                terminal = new TerminalDaoImpl(ctx, connectionSource, Terminal.class) {
                };
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return terminal;
    }

    public AirConditionDao getAirConditionDao() {
        if (airCondition == null) {
            try {
                airCondition = new AirConditionDaoImpl(ctx, connectionSource, AirCondition.class) {
                };
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return airCondition;
    }

    public UserDao getUserDao() {
        if (user == null) {
            try {
                user = new UserDaoImpl(ctx, connectionSource, User.class) {
                };
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return user;
    }

    public DeviceTerminalChooseDao getDeviceTerminalChooseDao() {
        if (choose == null) {
            try {
                choose = new DeviceTerminalChooseDaoImpl(ctx, connectionSource, DeviceTerminalChoose.class) {
                };
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return choose;
    }

    public UserFamilyRelationDao getUserFamilyRelationDao() {
        if (relation == null) {
            try {
                relation = new UserFamilyRelationDaoImpl(ctx, connectionSource, UserFamilyRelation.class) {
                };
            } cat
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

慕容屠苏

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值