Android ORM框架介绍之OrmLite注解与封装

时间:2022-08-31 19:49:21

Android ORM框架介绍之OrmLite注解与封装

OrmLite库引入

compile 'com.j256.ormlite:ormlite-android:5.0'

OrmLite注解

  • @DatabaseTable:用于javabean类上
public @interface DatabaseTable {
String tableName() default "";//设置表名,默认是类名

/**
* The DAO class that corresponds to this class. This is used by the {@link DaoManager} when it constructs a DAO
* internally.
*/

Class<?> daoClass() default Void.class;//Dao类与这个类相关联
}
  • DatabaseField:用于成员变量上
public @interface DatabaseField {
public static final int DEFAULT_MAX_FOREIGN_AUTO_REFRESH_LEVEL = 2;

String columnName() default "";//表中的字段名,不设置就默认为成员变量名

DataType dataType() default DataType.UNKNOWN;//数据类型

String defaultValue() default DEFAULT_STRING;//创建表时默认数据,默认none

int width() default 0;//字段的数据大小,常用于String

boolean canBeNull() default true;//设置字段不为空,默认true

boolean id() default false;//主键,唯一,如果不设置,不能使用query,update,delete的ID方法

boolean generatedId() default false;//自增的id,默认fasle

String generatedIdSequence() default "";//用于生成此值的序列号的名称,默认none

boolean foreign() default false;//外键,关联另一个类

boolean useGetSet() default false;//使用set/get方法访问字段值

String unknownEnumName() default "";//类中使用枚举,但数据库使用一个字段与之匹配

boolean throwIfNull() default false;//如果设置true,数据库字段为none,会抛出SQLException

boolean persisted() default true;//如果设置false,表示这个字段不写到数据库中

String format() default "";//可选的格式信息,可以使用不同的字段类型。

boolean unique() default false;//唯一字段,对于所有行

boolean uniqueCombo() default false;//唯一字段,对于所有列

boolean index() default false;//是否建立索引 默认为false

boolean uniqueIndex() default false;//唯一索引 默认为false

String indexName() default "";//为这一领域的索引添加一个名字

String uniqueIndexName() default "";// 为这一领域的索引添加一个唯一的名字

boolean foreignAutoRefresh() default false;//当查询到一个外键对象时,是否自动刷新

int maxForeignAutoRefreshLevel() default DEFAULT_MAX_FOREIGN_AUTO_REFRESH_LEVEL;//为了防止无限递归或者无限循环时 需要用到该属性设置自动刷新的*别

boolean allowGeneratedIdInsert() default false;//插入一个ID字段是否覆盖它生成的ID的对象 默认为false

String columnDefinition() default "";//定义列,默认情况下,数据库类型是用于自动生成所需的SQL来创建列,所以该属性并不常用

boolean foreignAutoCreate() default false;//在插入一个有外键对象的对象时,是否自动插入这个外键对象

boolean version() default false;//行版本 当一个对象被更新,以防止数据损坏多个实体时更新在同一时间进行的保护

String foreignColumnName() default "";//指定关联外键的字段名,取代使用id的用法,推荐使用

boolean readOnly() default false;//字段只读
}

ormlite的封装

  • DataBaseHelper:用于数据库的创建,表的创建和更新
public class DataBaseHelper extends OrmLiteSqliteOpenHelper {

private static final String DB_NAME = "my.db";
private static int VERSION = 1;
private static volatile DataBaseHelper helper;

private DataBaseHelper(Context context) {
super(context, DB_NAME, null, VERSION);
}

public static DataBaseHelper getInstance(Context context) {
if (helper == null) {
synchronized (DataBaseHelper.class) {
if (helper == null) {
helper = new DataBaseHelper(context);
}
}
}
return helper;
}

@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
//创建表,如果需要创建很多表,需要一个个写(这里不知道怎么抽取)
TableUtils.createTable(connectionSource, User.class);
} catch (SQLException e) {
e.printStackTrace();
}
}

@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
//类似创建
TableUtils.dropTable(connectionSource, User.class, true);
onCreate(database, connectionSource);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
  • DataBaseManager:管理数据库的增删改查操作
public class DataBaseManager<T> {
private volatile static DataBaseManager manager;
private Context context;
private Dao dao;

private DataBaseManager(Context context) {
this.context = context;
}

public static DataBaseManager getInstance(Context context) {
context = context.getApplicationContext();
if (manager == null) {
synchronized (DataBaseManager.class) {
if (manager == null) {
manager = new DataBaseManager(context);
}
}
}
return manager;
}

@SuppressWarnings("unchecked")
public DataBaseManager createDao(T t) {
try {
if (dao == null) {
dao = DataBaseHelper.getInstance(context).getDao(t.getClass());
}
return manager;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}

/**
* 如果插入的数据存在,会更新数据
*/

@SuppressWarnings("unchecked")
public int insert(T t) throws SQLException {
return dao.create(t);
}

@SuppressWarnings("unchecked")
public int insertAll(List<T> list) throws SQLException {

return dao.create(list);
}

@SuppressWarnings("unchecked")
public int update(T t) throws SQLException {

return dao.update(t);
}

@SuppressWarnings("unchecked")
public UpdateBuilder updateBuild(T t) throws SQLException {
return dao.updateBuilder();
}

@SuppressWarnings("unchecked")
public List<T> query(T t) throws SQLException {
return dao.queryForMatchingArgs(t);
}

@SuppressWarnings("unchecked")
public T queryT(T t) throws SQLException {
return (T) dao.queryForSameId(t);
}

@SuppressWarnings("unchecked")
public List<T> queryAll() throws SQLException {
return dao.queryForAll();
}

@SuppressWarnings("unchecked")
public QueryBuilder queryBuild() throws SQLException {
return dao.queryBuilder();
}

@SuppressWarnings("unchecked")
public int delete(T t) throws SQLException {
return dao.delete(t);
}

@SuppressWarnings("unchecked")
public int deleteAll(List<T> list) throws SQLException {
return dao.delete(list);
}

public void close() {
DataBaseHelper.getInstance(context).close();
dao = null;
}
}
  • User
@DatabaseTable(tableName = "tb_user")
public class User {
@DatabaseField(generatedId = true, unique = true)//自增,唯一
private long id;
@DatabaseField(columnName = "name")//数据库列名,如果不设置默认字段名
private String name;
@DatabaseField(columnName = "age",dataType = DataType.INTEGER)
private int age;

public User(long id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}

public User(){}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
  • MainActivity
package www.zhang.com.ormlite;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

@SuppressWarnings("unchecked")
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private DataBaseManager<User> manager;
private Button insert;
private Button update;
private Button query;
private Button queryAll;
private Button delete;
private Button deleteAll;
private TextView tv_query;
private TextView tv_queryall;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

insert = (Button) findViewById(R.id.btn1);
update = (Button) findViewById(R.id.btn2);
query = (Button) findViewById(R.id.btn3);
queryAll = (Button) findViewById(R.id.btn4);
delete = (Button) findViewById(R.id.btn5);
deleteAll = (Button) findViewById(R.id.btn6);

tv_query = (TextView) findViewById(R.id.tv_query);
tv_queryall = (TextView) findViewById(R.id.tv_queryall);

insert.setOnClickListener(this);
update.setOnClickListener(this);
query.setOnClickListener(this);
queryAll.setOnClickListener(this);
delete.setOnClickListener(this);
deleteAll.setOnClickListener(this);

try {
manager = DataBaseManager.getInstance(MainActivity.this).createDao(User.class.newInstance());
} catch (Exception e) {
e.printStackTrace();
}
}

private void deleteAll() {
try {
manager.deleteAll(manager.queryAll());
} catch (SQLException e) {
e.printStackTrace();
}
}

private void deleteData() {
try {
User user = new User();
user.setId(2);
manager.delete(user);
} catch (SQLException e) {
e.printStackTrace();
}
}

private List<User> queryAll() {
try {
return manager.queryAll();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}

private User queryData() {
try {
User user = new User();
user.setId(1);
return manager.queryT(user);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}

private void updateData() {
try {
User user = new User(1, "lisi", 25);
manager.update(user);
} catch (SQLException e) {
e.printStackTrace();
}
}

private void insertData() {
try {
User user1 = new User(1, "zhangsan", 20);
manager.insert(user1);
User user2 = new User(1, "zhangsan", 20);
manager.insert(user2);
User user3 = new User(1, "zhangsan", 20);
manager.insert(user3);
User user4 = new User(1, "zhangsan", 20);
manager.insert(user4);

} catch (SQLException e) {
e.printStackTrace();
}
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn1:
insertData();
break;
case R.id.btn2:
updateData();
break;
case R.id.btn3:
User user = queryData();
if (user == null) {
tv_query.setText("查询的数据不存在");
} else {
tv_query.setText(user.toString());
}
break;
case R.id.btn4:
List<User> list = queryAll();
if (list == null) {
tv_queryall.setText("查询的数据不存在");
} else {
tv_queryall.setText(list.toString());
}
break;
case R.id.btn5:
deleteData();
break;
case R.id.btn6:
deleteAll();
break;
}
}
}

Android ORM框架介绍之OrmLite注解与封装