android中如何在SQLite数据库中存储employee对象
我创建了一个Employee对象,其中的属性是name、lastname、phone等 现在我创建了一个对象 员工emp=新员工() 现在我想将emp对象存储到andriod中SQLite中的字节中 请帮我怎么做 我知道如何通过ContentValues插入值,但我不想创建一个包含50列的表。我只想保存类对象和 我想稍后再检索。您可以使用映射映射您的android中如何在SQLite数据库中存储employee对象,android,sqlite,Android,Sqlite,我创建了一个Employee对象,其中的属性是name、lastname、phone等 现在我创建了一个对象 员工emp=新员工() 现在我想将emp对象存储到andriod中SQLite中的字节中 请帮我怎么做 我知道如何通过ContentValues插入值,但我不想创建一个包含50列的表。我只想保存类对象和 我想稍后再检索。您可以使用映射映射您的员工类。您有很多选择: 作为示例,我将演示如何使用ORMLite映射对象 添加渐变依赖项: dependencies { com
员工
类。您有很多选择:
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();
List results=employeeDao.queryBuilder().where().eq(“firstName”、“employee_name”).query();
希望这有帮助。您需要能够将对象序列化为字节流,然后从字节流重新创建对象
然后,将该字节流存储在数据库中。您可以使用对象的json。它非常简单,您可以使用自由库,如显示您迄今为止的尝试……在sqlite上尝试一些示例。