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数据库对应的实体类与扩展口。
实现思路图:
![android的ORMLite的sqlite自定义框架_第1张图片](http://img.e-com-net.com/image/info8/0d2ea663b2ce4a99b780aefd55ce2dd0.jpg)
实现代码:
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 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 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) {
};
} catch (Exception e) {
e.printStackTrace();
}
}
return relation;
}
public DeviceTerminalRelationDao getDeviceTerminalRelationDao() {
if (relations == null) {
try {
relations = new DeviceTerminalRelationDaoImpl(ctx, connectionSource, DeviceTerminalRelation.class) {
};
} catch (Exception e) {
e.printStackTrace();
}
}
return relations;
}
public VoiceSetDao getVoiceSetDao() {
if (voices == null) {
try {
voices = new VoiceSetDaoImpl(ctx, connectionSource, VoiceSet.class);
} catch (Exception e) {
e.printStackTrace();
}
}
return voices;
}
public AlarmMessageDao getAlarmMessageDao() {
if (mAlarmMessageDao == null) {
try {
mAlarmMessageDao = new AlarmMessageDaoImpl(ctx, connectionSource, AlarmMessage.class) {
};
} catch (Exception e) {
e.printStackTrace();
}
}
return mAlarmMessageDao;
}
public ModeVoiceDao getModeVoiceDao() {
if (mVoices == null) {
try {
mVoices = new ModeVoiceDaoImpl(ctx, connectionSource, ModelVoice.class) {
};
} catch (Exception e) {
e.printStackTrace();
}
}
return mVoices;
}
public CombinationVoiceDao getCombinationVoiceDao() {
if (mCombination == null) {
try {
mCombination = new CombinationVoiceDaoImpl(ctx, connectionSource, CombinationVoice.class) {
};
} catch (Exception e) {
e.printStackTrace();
}
}
return mCombination;
}
public VideoUserDao getvUserDao() {
if (vUserDao == null) {
try {
vUserDao = new VideoUserDaoImpl(ctx, connectionSource, Video.class) {
};
} catch (Exception e) {
e.printStackTrace();
}
}
return vUserDao;
}
/**
* 清除APP数据,并发送广播
*/
public static void clearData() {
MainApplication context = MainApplication.getmApplication();
ConnectionSource con = getIntance(context).getConnectionSource();
try {
// SharedPreferences sharedPreferences = context.getSharedPreferences("JinXun", 0);
// SharedPreferences.Editor editor1 = sharedPreferences.edit();
// editor1.clear();
// editor1.commit();
boolean bl = true;
TableUtils.dropTable(con, Family.class, bl);
TableUtils.dropTable(con, DeviceState.class, bl);
TableUtils.dropTable(con, Device.class, bl);
TableUtils.dropTable(con, Model.class, bl);
TableUtils.dropTable(con, ModelInfo.class, bl);
TableUtils.dropTable(con, Room.class, bl);
TableUtils.dropTable(con, Terminal.class, bl);
TableUtils.dropTable(con, User.class, bl);
TableUtils.dropTable(con, DeviceTerminalChoose.class, bl);
TableUtils.dropTable(con, UserFamilyRelation.class, bl);
TableUtils.dropTable(con, DeviceTerminalRelation.class, bl);
TableUtils.dropTable(con, VoiceSet.class, bl);
TableUtils.dropTable(con, AlarmMessage.class, bl);
TableUtils.dropTable(con, ModelVoice.class, bl);
TableUtils.dropTable(con, Video.class, bl);
TableUtils.dropTable(con, CombinationVoice.class, bl);
TableUtils.dropTable(con, AirCondition.class, bl);
//创建表
TableUtils.createTable(con, Family.class);
TableUtils.createTable(con, DeviceState.class);
TableUtils.createTable(con, Device.class);
TableUtils.createTable(con, Model.class);
TableUtils.createTable(con, ModelInfo.class);
TableUtils.createTable(con, Room.class);
TableUtils.createTable(con, Terminal.class);
TableUtils.createTable(con, User.class);
TableUtils.createTable(con, DeviceTerminalChoose.class);
TableUtils.createTable(con, UserFamilyRelation.class);
TableUtils.createTable(con, DeviceTerminalRelation.class);
TableUtils.createTable(con, VoiceSet.class);
TableUtils.createTable(con, AlarmMessage.class);
TableUtils.createTable(con, ModelVoice.class);
TableUtils.createTable(con, Video.class);
TableUtils.createTable(con, CombinationVoice.class);
TableUtils.createTable(con, AirCondition.class);
execSQLByBatch(getIntance(context).getWritableDatabase());
} catch (Exception e) {
e.printStackTrace();
}
//发送清空数据广播
context.sendBroadcast(new Intent(notifyConstants.REFRESH_CLEAN_DATA_BROADCAST));
}
}
UserDao.java :
public interface UserDao extends Dao {
public void save(User id);
public void deleteAll();
public List getAll();
public List getAll2();
public void updateUser(String userId, String userType);
}
TerminalDao.java:
public interface TerminalDao extends Dao {
public void save(Terminal id);
/**
* 修改终端名称
*
* @param terminalList
*/
public void updateNameAll(List
DeviceDao.java:
public interface DeviceDao extends Dao {
public void save(Device id);
/**
* 获取当前房间所有设备列表
*
* @param room
* @return
*/
public List getDeviceListByRoom(Room room);
/**
* 获取模式列表中的设备
*
* @param room
* @return
*/
public List getDeviceListByModel(Room room);
/**
* 修改设备名称
*
* @param deviceList
*/
public void updateNameAll(List
UserDaoImpl.java:
public class UserDaoImpl extends BaseDaoImpl implements UserDao {
private DBHelper dbHelper;
public UserDaoImpl(Context ctx, ConnectionSource connectionSource, Class dataClass)
throws Exception {
super(connectionSource, dataClass);
dbHelper = DBHelper.getIntance(ctx);
}
@Override
public void save(User bean) {
// TODO Auto-generated method stub
try {
create(bean);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void deleteAll() {
SQLiteDatabase db = dbHelper.getWritableDatabase();
//修改SQL语句
String sql = "delete from t_user";
//执行SQL
db.execSQL(sql);
}
@Override
public List getAll() {
List list = null;
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c = db.query("t_user", null, null, null, null, null, null);
//查询并获得游标
if (c.moveToFirst()) {//判断游标是否为空
list = new ArrayList<>();
for (int i = 0; i < c.getCount(); i++) {
c.move(i);//移动到指定记录
User user = new User();
user.setId(c.getInt(c.getColumnIndex("id")));
user.setUserName(c.getString(c.getColumnIndex("f_user_name")));
user.setUserType(c.getString(c.getColumnIndex("f_user_type")));
user.setUserId(c.getString(c.getColumnIndex("f_user_id")));
user.setPassword(c.getString(c.getColumnIndex("f_user_password")));
user.setUserToken(c.getString(c.getColumnIndex("f_user_token")));
user.setIsextrusion(c.getString(c.getColumnIndex("f_user_isextrusion")));
user.setPhoneId(c.getString(c.getColumnIndex("f_phone_id")));
user.setIsaccredit(c.getString(c.getColumnIndex("f_user_accredit")));
user.setUser_group(c.getString(c.getColumnIndex("f_user_group")));
user.setIsquituser(c.getString(c.getColumnIndex("f_user_isquituser")));
list.add(user);
}
c.close();
}
return list;
}
@Override
public List getAll2() {
List list = null;
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c = db.query("t_user", null, null, null, null, null, null);
//查询并获得游标
if (c.moveToFirst()) {//判断游标是否为空
list = new ArrayList();
for (int i = 0; i < c.getCount(); i++) {
c.move(i);//移动到指定记录
User user = new User();
user.setId(c.getInt(c.getColumnIndex("id")));
user.setUserName(c.getString(c.getColumnIndex("f_user_name")));
user.setUserId(c.getString(c.getColumnIndex("f_user_id")));
// user.setUserType(c.getString(c.getColumnIndex("f_user_type")));
user.setPassword(c.getString(c.getColumnIndex("f_user_password")));
// user.setUserToken(c.getString(c.getColumnIndex("f_user_token")));
list.add(user);
}
c.close();
}
return list;
}
@Override
public void updateUser(String userId, String userType) {
}
}
TerminalDaoImpl.java:
public class TerminalDaoImpl extends BaseDaoImpl implements TerminalDao {
private DBHelper dbHelper;
protected TerminalDaoImpl(Context context, ConnectionSource connectionSource, Class dataClass) throws
SQLException {
super(connectionSource, dataClass);
dbHelper = DBHelper.getIntance(context);
}
@Override
public void saveAll(List terminalList) {
if (terminalList.size() > 0) {
for (int i = 0; i < terminalList.size(); i++) {
saveTerminalDevice(terminalList.get(i));
}
}
terminalList.clear();
}
@Override
public void updateNameAll(List
DeviceDaoImpl.java:
public class DeviceDaoImpl extends BaseDaoImpl implements DeviceDao {
private DBHelper dbHelper;
public DeviceDaoImpl(Context context, ConnectionSource connectionSource, Class dataClass) throws
SQLException {
super(connectionSource, dataClass);
dbHelper = DBHelper.getIntance(context);
}
@Override
public List getDeviceListByRoom(Room room) {
List list = null;
Map map = new HashMap();
map.put("f_family_id", room.getFamilyId());
map.put("f_room_id", room.getRoomId());
try {
list = queryForFieldValues(map);
} catch (Exception e) {
return list;
}
return list;
}
@Override
public void save(Device id) {
try {
create(id);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void updateNameAll(List