我创建了一个Employee对象,其中属性是name,lastname,phone等。
现在我创建了对象
员工emp =新员工();
现在我希望将商店emp对象转换为andriod中的SQLite中的字节。
请帮助我如何实现?
我知道如何通过ContentValues插入值,但我不想创建一个包含50个cols的表。我只想保存类Object和 我想稍后检索它。
答案 0 :(得分:2)
您可以使用ORM (Object-Relational Mapping)来映射Employee
课程。你有很多选择:
作为一个例子,我将展示如何使用ORMLite来映射你的对象。
添加Gradle依赖项:
dependencies {
compile 'com.j256.ormlite:ormlite-android:4.48'
}
映射您的实体员工:
@DatabaseTable(tableName = "employee")
public class Employee implements Serializable {
@DatabaseField(generatedId = true)
private long id;
@DatabaseField
private String firstName;
@DatabaseField
private String lastName;
@DatabaseField
private int phoneNumber;
/**
* Add here the other attributes of the entity. Then, add the get and set methods.
*/
}
创建您的ORM助手:
public class OrmLiteHelper extends OrmLiteSqliteOpenHelper {
private static final String DATABASE_NAME = "your_app_name.db";
private static final int DATABASE_VERSION = 1;
private static OrmLiteHelper mInstance = null;
public OrmLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
try {
// TODO: Add all your entities here, to create the tables.
TableUtils.createTable(connectionSource, Employee.class);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
// TODO: Add all your entities here, to drop and recreate then.
TableUtils.dropTable(connectionSource, Employee.class, true);
onCreate(db, connectionSource);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public static OrmLiteHelper getInstance(Context context) {
if (mInstance == null) {
mInstance = new OrmLiteHelper(context.getApplicationContext());
}
return mInstance;
}
public RuntimeExceptionDao getRuntimeDao(Class model) {
return getRuntimeExceptionDao(model);
}
}
要访问数据库数据,请为实体创建DAO:
RuntimeExceptionDao<Employee, Integer> employeeDao = OrmLiteHelper.getInstance(context).getRuntimeDao(Employee.class);
现在很容易坚持实体:
employeeDao.createOrUpdate(employee);
甚至更容易检索您的实体:
List<Employee> results = employeeDao.queryBuilder().where().eq("firstName", "employee_name").query();
希望这有帮助。
答案 1 :(得分:0)
您需要能够将对象序列化为字节流,然后从字节流中重新创建对象。
然后,只需将该字节流存储在数据库中。