Ormlite 是一个开源Java数据实体映射框架。其中依赖2个核心类库:
新建项目,引用上面2个类库,开始第一个Helloword。
新建一个实体类Users.java,实体类必须有一个无参构造函数。
package com.example.model; import com.j256.ormlite.dao.ForeignCollection; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.field.ForeignCollectionField; import com.j256.ormlite.table.DatabaseTable; @DatabaseTable(tableName = "accounts") public class Users { @DatabaseField(id=true) private String uid; public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } @DatabaseField(canBeNull = false) private String username; @DatabaseField(canBeNull = true) private String name; public Users(){} }
要实现数据访问必须得对数据进行访问。新建一个类:DataHelp.java,该类类似于SqliteDatabaseOpenHelpe
package com.example.data; import java.sql.SQLException; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.util.Log; import com.example.model.Users; import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.TableUtils; public class DataHelper extends OrmLiteSqliteOpenHelper { public DataHelper(Context context, String databaseName, CursorFactory factory, int databaseVersion) { super(context, databaseName, factory, databaseVersion); } @Override public void onCreate(SQLiteDatabase db, ConnectionSource conn) { try { // 完成初始化表。 TableUtils.createTable(conn, Users.class); } catch (SQLException e) { e.printStackTrace(); Log.e("chenrui", "表创建失败:" + e.getMessage()); } } @Override public void onUpgrade(SQLiteDatabase arg0, ConnectionSource arg1, int arg2, int arg3) { } }
完成了数据的创建,接下来就是操作具体的表了。在DataHelp.java 中添加下面的方法轻松创建一个操作数据库的接口。泛型接口中Dao<T,ID> 中ID为主键类型。
public Dao<Users, String> getUser() throws SQLException { if (user == null) user = this.getDao(Users.class); return user; }
最后程序调用。
public void testCreate() throws SQLException { Dao<Users, String> dao = DataFactory.getFactory(mContext).getUser(); // 这里使用工厂调用。你也可以 new DataHelp(context,"test.db",null,1).getUser();
Users m = new Users(); m.setName("陈rui"); m.setUid("1234"); m.setUsername("chenrui"); dao.create(m); }