效果图:

 Android开发 ---ORMLite实现数据的增删改查,单例模式,Dao栈-LMLPHP

项目目录截图:

Android开发 ---ORMLite实现数据的增删改查,单例模式,Dao栈-LMLPHP

1、activity_main.xml

  描述:

    两行显示8个按钮

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:text="添加用户"
android:onClick="addUser"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="wrap_content" />
<Button
android:text="查询用户"
android:onClick="findUserList"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="wrap_content" />
<Button
android:text="删除用户"
android:onClick="deleteUser"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="wrap_content" />
<Button
android:text="修改用户"
android:onClick="updateUser"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="wrap_content" />
</LinearLayout> <LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:text="添加部门"
android:onClick="addDept"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="wrap_content" />
<Button
android:text="查询部门"
android:onClick="findDeptList"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="wrap_content" />
<Button
android:text="添加员工"
android:onClick="addEmp"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="wrap_content" />
<Button
android:text="查询员工"
android:onClick="findEmpList"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>

2、MainActivity.java

package com.nf.android_ormlite;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast; import com.nf.dao.DeptDao;
import com.nf.dao.EmpDao;
import com.nf.dao.UsersDao;
import com.nf.entity.TbDept;
import com.nf.entity.TbEmp;
import com.nf.entity.Users; import java.sql.SQLException;
import java.util.Date;
import java.util.List; public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//添加用户操作
//new一个Users将用户的编号、用户名、密码、日期封装起来交给UsersDao里的addUsers()方法进行添加用户的操作
//添加成功返回结果并弹出提示
public void addUser(View view) throws SQLException {
boolean res=new UsersDao(this).addUsers(new Users(0,"abc","123123",new Date()));
Toast.makeText(this, "添加用户结果是:"+res, Toast.LENGTH_SHORT).show();
}
//查询用户信息列表的操作
//调用UsersDao里的getUserList()方法从数据库中获取到所有用户的信息,保存到list集合中
public void findUserList(View view) throws SQLException {
List<Users> users=new UsersDao(this).getUserList();
//对list集合进行循环遍历,取出用户编号、用户名称、用户密码写入日志中
for (Users user:users){
Log.i("FindUserList:",user.get_id()+","+user.getUname()+","+user.getUpwd());
}
}
//根据用户ID删除用户信息的操作
//调用UserDao中的deleteUsers()方法传入一个用户ID,删除该ID对应的用户信息
public void deleteUser(View view) throws SQLException {
UsersDao dao=new UsersDao(this);
Users user=dao.getUserById(3);
boolean res=new UsersDao(this).deleteUsers(user);
Toast.makeText(this, "删除用户结果是:"+res, Toast.LENGTH_SHORT).show();
}
//修改用户信息的操作
//调用UserDao的updateUsers()方法将编号为2的用户的用户名称修改为Toms
public void updateUser(View view) throws SQLException { UsersDao dao=new UsersDao(this);
Users user=dao.getUserById(2);
user.setUname("Toms");
boolean res=dao.updateUsers(user);
Toast.makeText(this, "修改用户结果是:"+res, Toast.LENGTH_SHORT).show();
}
//添加部门的操作
//调用DeptDaod的addDept()方法添加一个学工部
public void addDept(View view) throws SQLException {
TbDept dept=new TbDept(0,"学工部");
new DeptDao(this).addDept(dept);
Toast.makeText(this, "添加部门成功", Toast.LENGTH_SHORT).show();
}
//查询部门的操作
//调用DeptDao的findDeptList()方法从数据库中获取所有的部门信息放入list集合中
public void findDeptList(View view) throws SQLException {中心
List<TbDept> list=new DeptDao(this).findDeptList();
//对list集合进行循环遍历,获取出部门编号、部门名称、该部门员工的人数
for(TbDept dept:list){
Log.i("DeptList:",dept.get_id()+","+dept.getDname()+","+dept.getEmps().size());
}
}
//添加员工的操作
//调用TbEmp()实体对象封装一名员工信息
//再调用EmpDao中的addEmp()方法将员工信息添加到数据库
//我们在员工表里再绑定他所在的部门
public void addEmp(View view) throws SQLException {
TbEmp emp=new TbEmp(0,"Kite",22,"男");
//取出学术部
TbDept dept=new DeptDao(this).getDeptById(2);
//绑定员工和部门
emp.setDept(dept);
//保存员工
new EmpDao(this).addEmp(emp);
Toast.makeText(this, "添加员工成功", Toast.LENGTH_SHORT).show();
}
//查询员工信息的操作
//调用EmpDao中的findempList()方法从数据库中查询出来放入list集合
public void findEmpList(View v) throws Exception{
List<TbEmp> emps=new EmpDao(this).findEmpList();
//退list集合进行循环遍历,查询出所有员工的编号、姓名、部门名称
for (TbEmp emp:emps){
Log.i("EmpList:",emp.get_id()+","+emp.getEname()+","+emp.getDept().getDname());
}
}
}

3、dao/DeptDao.java

package com.nf.dao;
import android.content.Context; import com.nf.entity.TbDept;
import com.nf.utils.DbHelper; import java.sql.SQLException;
import java.util.List; public class DeptDao { private DbHelper dbHelper;
public DeptDao(Context context){
     //实例化DbHelper
dbHelper=DbHelper.getInstance(context);
} public boolean addDept(TbDept dept) throws SQLException {
     //通过dbHelper调用getDaos()
dbHelper.getDaos(TbDept.class).create(dept);
return true;
} public List findDeptList() throws SQLException {
return dbHelper.getDaos(TbDept.class).queryForAll();
} public TbDept getDeptById(int id) throws SQLException {
return (TbDept) dbHelper.getDaos(TbDept.class).queryForId(id);
}
}

4、dao/EmpDao.java

package com.nf.dao;
import android.content.Context; import com.nf.entity.TbEmp;
import com.nf.utils.DbHelper; import java.sql.SQLException;
import java.util.List; /**
* Created by Administrator on 2017/12/13.
*/ public class EmpDao { private DbHelper dbHelper;
public EmpDao(Context context){
dbHelper=DbHelper.getInstance(context);
} public boolean addEmp(TbEmp emp) throws SQLException {
dbHelper.getDaos(TbEmp.class).create(emp);
return true;
} public List findEmpList() throws SQLException {
return dbHelper.getDaos(TbEmp.class).queryForAll();
}
}

5、dao/UsersDao.java

package com.nf.dao;
import android.content.Context; import com.nf.entity.Users;
import com.nf.utils.DbHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.UpdateBuilder; import java.sql.SQLException;
import java.util.List; /**
* Created by Administrator on 2017/12/13.
*/ public class UsersDao { private DbHelper dbHelper;
private Dao dao;//DbHelper对象提供的一个对象持久化类
public UsersDao(Context context){
dbHelper=new DbHelper(context);
try {
dao=dbHelper.getDao(Users.class);
} catch (SQLException e) {
e.printStackTrace();
}
} //添加一个用户
public boolean addUsers(Users user) throws SQLException {
dao.create(user);
return true;
} //修改一个用户
public boolean updateUsers(Users user) throws SQLException {
dao.update(user);
return true;
} //删除一个用户
public boolean deleteUsers(Users user) throws SQLException {
dao.delete(user);
return true;
} public Users getUserById(int id) throws SQLException {
Users user=(Users) dao.queryForId(id);
return user;
} public List getUserList() throws SQLException {
List list=dao.queryForAll();
return list;
} //==============批量操作=============//
public boolean addUsers(List<Users> users) throws SQLException {
dao.create(users);
return true;
}
public boolean deleteUsers(List<Users> users) throws SQLException {
dao.delete(users);
return true;
} //==============带条件修改删除查询=============//
public boolean updateUsersByPwd(String query) throws SQLException {
UpdateBuilder builder=dao.updateBuilder();
builder.where().like("upwd",query);
builder.updateColumnValue("upwd","123456");
builder.update();
return true;
} public boolean deleteUsers(String name) throws SQLException {
DeleteBuilder builder=dao.deleteBuilder();
builder.where().eq("uname",name);
builder.delete();
return true;
}
public List findUserList(String name) throws SQLException {
QueryBuilder builder=dao.queryBuilder();
builder.where().like("uname","%"+name+"%");
builder.orderBy("uintime",true);
List list=builder.query();
return list;
}
}

6、entity/TbDept.java

package com.nf.entity;
import com.j256.ormlite.dao.ForeignCollection;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.field.ForeignCollectionField;
import com.j256.ormlite.table.DatabaseTable; import java.io.Serializable; @DatabaseTable(tableName = "tb_dept") //通过注解的方式设置部门表的表名
public class TbDept implements Serializable { @DatabaseField(generatedId = true)//设置部门编号 generatedId = true表示编号自动增长
private int _id;
@DatabaseField //默认设置
private String dname; //一对多的关系
@ForeignCollectionField(eager = false)
private ForeignCollection<TbEmp> emps; public TbDept() {
} public TbDept(int _id, String dname) {
this._id = _id;
this.dname = dname;
} public int get_id() {
return _id;
} public void set_id(int _id) {
this._id = _id;
} public String getDname() {
return dname;
} public void setDname(String dname) {
this.dname = dname;
} public ForeignCollection<TbEmp> getEmps() {
return emps;
} public void setEmps(ForeignCollection<TbEmp> emps) {
this.emps = emps;
}
}

7、entity/TbEmp.java

package com.nf.entity;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable; import java.io.Serializable;
//指定表名称
@DatabaseTable(tableName = "tb_emp")
public class TbEmp implements Serializable { @DatabaseField(generatedId = true)
private int _id;
@DatabaseField
private String ename;
@DatabaseField
private int eage;
@DatabaseField
private String esex; //多对一的关系
@DatabaseField(columnName = "edno",foreign = true,foreignAutoRefresh = true,canBeNull = false)
private TbDept dept; public TbEmp() {
} public TbEmp(int _id, String ename, int eage, String esex) {
this._id = _id;
this.ename = ename;
this.eage = eage;
this.esex = esex;
} public int get_id() {
return _id;
} public void set_id(int _id) {
this._id = _id;
} public String getEname() {
return ename;
} public void setEname(String ename) {
this.ename = ename;
} public int getEage() {
return eage;
} public void setEage(int eage) {
this.eage = eage;
} public String getEsex() {
return esex;
} public void setEsex(String esex) {
this.esex = esex;
} public TbDept getDept() {
return dept;
} public void setDept(TbDept dept) {
this.dept = dept;
}
}

8、entity/Users.java

package com.nf.entity;

import com.j256.ormlite.field.DataType;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable; import java.io.Serializable;
import java.util.Date; /**
* Created by Administrator on 2017/12/13.
*/
@DatabaseTable(tableName = "tb_users")
public class Users implements Serializable{
   //指定该字段为主键且自动增长
@DatabaseField(generatedId = true)
private int _id;
   //指定字段不能为空
@DatabaseField(canBeNull = false)
private String uname;
@DatabaseField(canBeNull = false)
private String upwd;
@DatabaseField(dataType = DataType.DATE)
private Date uintime; public Users() {
} public Users(int _id, String uname, String upwd, Date uintime) {
this._id = _id;
this.uname = uname;
this.upwd = upwd;
this.uintime = uintime;
} public int get_id() {
return _id;
} public void set_id(int _id) {
this._id = _id;
} public String getUname() {
return uname;
} public void setUname(String uname) {
this.uname = uname;
} public String getUpwd() {
return upwd;
} public void setUpwd(String upwd) {
this.upwd = upwd;
} public Date getUintime() {
return uintime;
} public void setUintime(Date uintime) {
this.uintime = uintime;
}
}

9、DbHelper.java

package com.nf.utils;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.Toast; import com.nf.entity.TbDept;
import com.nf.entity.TbEmp;
import com.nf.entity.Users;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils; import java.util.Date;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
//构建一个DbHelper类继承OrmLiteSqliteOpenHelper 实现对数据库的操作
public class DbHelper extends OrmLiteSqliteOpenHelper {
//定义数据库名称
private static final String DATABASE_NAME="ormlite.db";
//定义数据库的版本
private static final int VERSION=3;
//构造器,将上下文对象、数据库名称、工厂、版本信息初始化
public DbHelper(Context context) {//用于通过注解+反射创建数据库表
super(context, DATABASE_NAME, null, VERSION);//用于通过读取配置文件创建数据库表
}
private DbHelper(Context context, String databaseName, SQLiteDatabase.CursorFactory factory, int databaseVersion) {
super(context, DATABASE_NAME, null, VERSION);
} //第一次创建数据库时执行
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
//创建表Tb_users
TableUtils.createTableIfNotExists(connectionSource, Users.class);
//创建表Tb_dept
TableUtils.createTableIfNotExists(connectionSource, TbDept.class);
//创建表Tb_emp
TableUtils.createTableIfNotExists(connectionSource, TbEmp.class);
} catch (SQLException e) {
e.printStackTrace();
} //加入测试数据
try {
//调用Dao中的getDao()方法传入一个实体对象,实体对象里封装一个用户,通过create()方法,将这个用户初始化到tb_users数据表中
Dao dao=getDao(Users.class);//创建一个Users类的Dao
dao.create(new Users(0,"admins","admins",new Date()));
} catch (SQLException e) {
e.printStackTrace();
}
Log.i("create table","创建数据表成功");
} @Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
TableUtils.dropTable(connectionSource,Users.class,true);
TableUtils.dropTable(connectionSource,TbEmp.class,true);
TableUtils.dropTable(connectionSource,TbDept.class,true);
onCreate(database,connectionSource);
} catch (SQLException e) {
e.printStackTrace();
}
} //===================提供单例模式DbHelper对象提供服务=========================//
private static DbHelper dbHelper; public static synchronized DbHelper getInstance(Context context){
if(dbHelper==null){
dbHelper=new DbHelper(context);
}
return dbHelper;
} //==================构建一个Dao栈,统一管理Dao=======================//
private Map<String,Dao> daos=new HashMap<String,Dao>(); public Dao getDaos(Class cls) throws SQLException {
String className=cls.getName();//获取类名
if(!daos.containsKey(className)){
daos.put(className,super.getDao(cls));
}
return daos.get(className);
} //重写DbHelper的close方法
@Override
public void close() {
super.close();
Iterator it=daos.keySet().iterator();
while(it.hasNext()){
Dao dao=(Dao) it.next();
dao=null;
}
}
}
05-11 11:13
查看更多