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;
}
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;
int width() default 0;
boolean canBeNull() default true;
boolean id() default false;
boolean generatedId() default false;
String generatedIdSequence() default "";
boolean foreign() default false;
boolean useGetSet() default false;
String unknownEnumName() default "";
boolean throwIfNull() default false;
boolean persisted() default true;
String format() default "";
boolean unique() default false;
boolean uniqueCombo() default false;
boolean index() default false;
boolean uniqueIndex() default false;
String indexName() default "";
String uniqueIndexName() default "";
boolean foreignAutoRefresh() default false;
int maxForeignAutoRefreshLevel() default DEFAULT_MAX_FOREIGN_AUTO_REFRESH_LEVEL;
boolean allowGeneratedIdInsert() default false;
String columnDefinition() default "";
boolean foreignAutoCreate() default false;
boolean version() default false;
String foreignColumnName() default "";
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;
}
}
@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 +
'}';
}
}
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;
}
}
}