准备工作
我们需要从ormlite官网上下载我们需要的jar包http://ormlite.com/
我下载的jar包如图所示:
创建orm实体类
package com.lulu.lormlite;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
/**
* 完成对象关系映射orm的实体类
* 1, 对表名需要加注解
* 2, 对属性也需要加注解
* Created by Lulu on 2016/6/14.
*/
//该注解说明,跟数据库的某个表对应, 对应的表名为Student, 可以改掉( @DatabaseTable("xuesheng") )
@DatabaseTable
public class Student {
//指定不能为空, 该字段为主键并且自动增长(该情况下canBeNull可以不加)
@DatabaseField(canBeNull = false, generatedId = true)
private int id;
@DatabaseField(canBeNull = false)
private String
name;
//必须加上该无参构造方法
public Student() {
}
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
创建数据库辅助类
package com.lulu.lormlite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import java.sql.SQLException;
/**
* Created by Lulu on 2016/6/14.
*/
public class DbHelper extends OrmLiteSqliteOpenHelper{
public DbHelper(Context context) {
super(context, "xs.db", null, 1);
}
/**
* 当数据库不存在的时候
* 在该方法主要用于建表操作
* @param sqLiteDatabase
* @param connectionSource
*/
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, Student.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 数据库的升级,对比版本号
* @param sqLiteDatabase
* @param connectionSource
* @param i
* @param i1
*/
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) {
}
}
获取dao , 测试
package com.lulu.lormlite;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.j256.ormlite.dao.Dao;
import java.sql.SQLException;
//使用OrmLiteBaseActivity做为Activity
public class MainActivity extends OrmLiteBaseActivity<DbHelper> {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
DbHelper h = getHelper();
//获取相应dao
Dao<Student, Integer> sDao = h.getDao(Student.class);
//添加数据
sDao.create(new Student(1, "鹿鹿"));
} catch (SQLException e) {
e.printStackTrace();
}
}
}
注: 该博客只是简单的介绍一下该三方工具类, 详细功能(如, 外键,事务操作等)请见该jar包文档