安卓里的List<DBTable_User> list = dao.queryForFieldinsert into valuess(map);是什么意思

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
您的访问请求被拒绝 403 Forbidden - ITeye技术社区
您的访问请求被拒绝
亲爱的会员,您的IP地址所在网段被ITeye拒绝服务,这可能是以下两种情况导致:
一、您所在的网段内有网络爬虫大量抓取ITeye网页,为保证其他人流畅的访问ITeye,该网段被ITeye拒绝
二、您通过某个代理服务器访问ITeye网站,该代理服务器被网络爬虫利用,大量抓取ITeye网页
请您点击按钮解除封锁&16900人阅读
Android开发(46)
首先说明一下,本人已经使用ormlite-android做过两个大型的项目开发,很久以来就想对此数据库做一些总结,正好今天有空就写出来:
1. 首先去官网看官方说明,也可以去下载两个包:一个是ormlite-core-4.24.jar,另一个是ormlite-android-4.24.jar
2. 下载完2个jar包后导入项目中,在此不多说,大家都懂的
3.前奏工作完成,下面就是怎么去搭建框架使用了,首先说明本人做过一段时间的web开发,所以喜欢用mvc模式,下面将通过代码来说明:
&& 1).建立自己的DatabaseHelper类
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
// name of the database file for your application -- change to something
// appropriate for your app
private static final String DATABASE_NAME = &CHENGYIJI.db&;
// any time you make changes to your database objects, you may have to
// increase the database version
private static final int DATABASE_VERSION = 1;
// the DAO object we use to access the SimpleData table
//数据库默认路径SDCard
private static String DATABASE_PATH = Environment.getExternalStorageDirectory()
+ &/CHENGYIJI.db&;
private Context mC
//数据库配置文件默认路径SDCard
private static String DATABASE_PATH_JOURN = Environment.getExternalStorageDirectory()
+ &/CHEYIJI.db-journal&;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mContext =
initDtaBasePath();
File f = new File(DATABASE_PATH);
if (!f.exists()) {
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(DATABASE_PATH, null);
onCreate(db);
db.close();
} catch (Exception e) {
//如果没有SDCard 默认存储在项目文件目录下
private void initDtaBasePath() {
if (!Utils.ExistSDCard()) {
DATABASE_PATH = mContext.getFilesDir().getAbsolutePath() + &/CHENGYIJI.db&;
DATABASE_PATH_JOURN = mContext.getFilesDir().getAbsolutePath() + &/CHEYIJI.db-journal&;
public synchronized SQLiteDatabase getWritableDatabase() {
return SQLiteDatabase.openDatabase(DATABASE_PATH, null, SQLiteDatabase.OPEN_READWRITE);
public synchronized SQLiteDatabase getReadableDatabase() {
return SQLiteDatabase.openDatabase(DATABASE_PATH, null, SQLiteDatabase.OPEN_READONLY);
* This is called when the database is first created. Usually you should
* call createTable statements here to create the tables that will store
* your data.
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
LogTool.i(DatabaseHelper.class.getName(), &onCreate&);
TableUtils.createTable(connectionSource, UserInfo.class);
} catch (java.sql.SQLException e) {
LogTool.e(DatabaseHelper.class.getName(), &Can't create database&, e);
throw new RuntimeException(e);
* This is called when your application is upgraded and it has a higher
* version number. This allows you to adjust the various data to match the
* new version number.
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion,
int newVersion) {
LogTool.i(DatabaseHelper.class.getName(), &onUpgrade&);
TableUtils.dropTable(connectionSource, UserInfo.class, true);
onCreate(db, connectionSource);
} catch (java.sql.SQLException e) {
LogTool.e(DatabaseHelper.class.getName(), &Can't drop databases&, e);
throw new RuntimeException(e);
public void deleteDB() {
if (mContext != null) {
File f = mContext.getDatabasePath(DATABASE_NAME);
if (f.exists()) {
// mContext.deleteDatabase(DATABASE_NAME);
LogTool.e(&DB&, &---delete SDCard DB---&);
f.delete();
LogTool.e(&DB&, &---delete App DB---&);
mContext.deleteDatabase(DATABASE_NAME);
File file = mContext.getDatabasePath(DATABASE_PATH);
if (file.exists()) {
LogTool.e(&DB&, &---delete SDCard DB 222---&);
file.delete();
File file2 = mContext.getDatabasePath(DATABASE_PATH_JOURN);
if (file2.exists()) {
LogTool.e(&DB&, &---delete SDCard DB 333---&);
file2.delete();
* Close the database connections and clear any cached DAOs.
public void close() {
super.close();
}&2)创建自己的数据库操作Dao层】public abstract class BaseDao&T, Integer& {
protected DatabaseHelper mDatabaseH
protected Context mC
public BaseDao(Context context) {
mContext =
getHelper();
public DatabaseHelper getHelper() {
if (mDatabaseHelper == null) {
mDatabaseHelper = OpenHelperManager.getHelper(mContext, DatabaseHelper.class);
return mDatabaseH
public abstract Dao&T, Integer& getDao() throws SQLE
public int save(T t) throws SQLException {
return getDao().create(t);
public List&T& query(PreparedQuery&T& preparedQuery) throws SQLException {
Dao&T, Integer& dao = getDao();
return dao.query(preparedQuery);
public List&T& query(String attributeName, String attributeValue) throws SQLException {
QueryBuilder&T, Integer& queryBuilder = getDao().queryBuilder();
queryBuilder.where().eq(attributeName, attributeValue);
PreparedQuery&T& preparedQuery = queryBuilder.prepare();
return query(preparedQuery);
public List&T& query(String[] attributeNames, String[] attributeValues) throws SQLException,
InvalidParamsException {
if (attributeNames.length != attributeValues.length) {
throw new InvalidParamsException(&params size is not equal&);
QueryBuilder&T, Integer& queryBuilder = getDao().queryBuilder();
Where&T, Integer& wheres = queryBuilder.where();
for (int i = 0; i & attributeNames. i++) {
wheres.eq(attributeNames[i], attributeValues[i]);
PreparedQuery&T& preparedQuery = queryBuilder.prepare();
return query(preparedQuery);
public List&T& queryAll() throws SQLException {
// QueryBuilder&T, Integer& queryBuilder = getDao().queryBuilder();
// PreparedQuery&T& preparedQuery = queryBuilder.prepare();
// return query(preparedQuery);
Dao&T, Integer& dao = getDao();
return dao.queryForAll();
public T queryById(String idName, String idValue) throws SQLException {
List&T& lst = query(idName, idValue);
if (null != lst && !lst.isEmpty()) {
return lst.get(0);
public int delete(PreparedDelete&T& preparedDelete) throws SQLException {
Dao&T, Integer& dao = getDao();
return dao.delete(preparedDelete);
public int delete(T t) throws SQLException {
Dao&T, Integer& dao = getDao();
return dao.delete(t);
public int delete(List&T& lst) throws SQLException {
Dao&T, Integer& dao = getDao();
return dao.delete(lst);
public int delete(String[] attributeNames, String[] attributeValues) throws SQLException,
InvalidParamsException {
List&T& lst = query(attributeNames, attributeValues);
if (null != lst && !lst.isEmpty()) {
return delete(lst);
public int deleteById(String idName, String idValue) throws SQLException,
InvalidParamsException {
T t = queryById(idName, idValue);
if (null != t) {
return delete(t);
public int update(T t) throws SQLException {
Dao&T, Integer& dao = getDao();
return dao.update(t);
public boolean isTableExsits() throws SQLException {
return getDao().isTableExists();
public long countOf() throws SQLException {
return getDao().countOf();
public List&T& query(Map&String, Object& map) throws SQLException {
QueryBuilder&T, Integer& queryBuilder = getDao().queryBuilder();
if (!map.isEmpty()) {
Where&T, Integer& wheres = queryBuilder.where();
Set&String& keys = map.keySet();
ArrayList&String& keyss = new ArrayList&String&();
keyss.addAll(keys);
for (int i = 0; i & keyss.size(); i++) {
if (i == 0) {
wheres.eq(keyss.get(i), map.get(keyss.get(i)));
wheres.and().eq(keyss.get(i), map.get(keyss.get(i)));
PreparedQuery&T& preparedQuery = queryBuilder.prepare();
return query(preparedQuery);
public List&T& query(Map&String, Object& map, Map&String, Object& lowMap,
Map&String, Object& highMap) throws SQLException {
QueryBuilder&T, Integer& queryBuilder = getDao().queryBuilder();
Where&T, Integer& wheres = queryBuilder.where();
if (!map.isEmpty()) {
Set&String& keys = map.keySet();
ArrayList&String& keyss = new ArrayList&String&();
keyss.addAll(keys);
for (int i = 0; i & keyss.size(); i++) {
if (i == 0) {
wheres.eq(keyss.get(i), map.get(keyss.get(i)));
wheres.and().eq(keyss.get(i), map.get(keyss.get(i)));
if (!lowMap.isEmpty()) {
Set&String& keys = lowMap.keySet();
ArrayList&String& keyss = new ArrayList&String&();
keyss.addAll(keys);
for (int i = 0; i & keyss.size(); i++) {
if(map.isEmpty()){
wheres.gt(keyss.get(i), lowMap.get(keyss.get(i)));
wheres.and().gt(keyss.get(i), lowMap.get(keyss.get(i)));
if (!highMap.isEmpty()) {
Set&String& keys = highMap.keySet();
ArrayList&String& keyss = new ArrayList&String&();
keyss.addAll(keys);
for (int i = 0; i & keyss.size(); i++) {
wheres.and().lt(keyss.get(i), highMap.get(keyss.get(i)));
PreparedQuery&T& preparedQuery = queryBuilder.prepare();
return query(preparedQuery);
3)怎么应用
首先有一个model对象public class CashFlow implements ICashFlowRecorder, Serializable {
&&& private static final long serialVersionUID = 1L;&&& // 流水号ID
&&& @DatabaseField(generatedId = true, columnName = &cash_flow_id&)
&&& private long cashFlowId;&&& // 类型:0收,1支
&&& @DatabaseField(canBeNull = false, columnName = &type&)
&&&&&& // 资金类型 - 0 贷款,1借款,2货款,3其他
&&& @DatabaseField(canBeNull = false, columnName = &cash_type&)
&&& private int cashT&&& // 资金类型为其他是的 描述
&&& @DatabaseField(columnName = &other_type_desc&)
&&& private String otherTypeD&&& // 是否参与核销:0否,1是
&&& @DatabaseField(canBeNull = false, columnName = &write_off_flag&)
&&& private int writeOffF&&& // 关联用户ID
&&& // private long referUserId;
&&& @DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = &phone_book_id&)
&&& private PhoneBook referU&&& // 资金
&&& @DatabaseField(canBeNull = false, columnName = &amount&)
&&& p&&& // 登记日期
&&& @DatabaseField(canBeNull = false, columnName = &reg_date&)
&&& private long regD&&& // 创建时间
&&& @DatabaseField(canBeNull = false, columnName = &create_date&)
&&& private long createD&&& // 修改时间
&&& @DatabaseField(canBeNull = false, columnName = &update_date&)
&&& private long updateD&&& // 关联账单ID
&&& @DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = &bill_id&)
&&& private Bill referB&&& public long getCashFlowId() {
&&&&&&& return cashFlowId;
&&& }&&& public void setCashFlowId(long cashFlowId) {
&&&&&&& this.cashFlowId = cashFlowId;
&&& }&&& public int getType() {
&&& }&&& public void setType(int type) {
&&&&&&& this.type =
&&& }&&& public int getCashType() {
&&&&&&& return cashT
&&& }&&& public void setCashType(int cashType) {
&&&&&&& this.cashType = cashT
&&& }&&& public String getOtherTypeDesc() {
&&&&&&& return otherTypeD
&&& }&&& public void setOtherTypeDesc(String otherTypeDesc) {
&&&&&&& this.otherTypeDesc = otherTypeD
&&& }&&& public int getWriteOffFlag() {
&&&&&&& return writeOffF
&&& }&&& public void setWriteOffFlag(int writeOffFlag) {
&&&&&&& this.writeOffFlag = writeOffF
&&& }&&& public PhoneBook getReferUser() {
&&&&&&& return referU
&&& }&&& public void setReferUser(PhoneBook referUser) {
&&&&&&& this.referUser = referU
&&& }&&& public double getAmount() {
&&& }&&& public void setAmount(double amount) {
&&&&&&& this.amount =
&&& }&&& public long getRegDate() {
&&&&&&& return regD
&&& }&&& public void setRegDate(long regDate) {
&&&&&&& this.regDate = regD
&&& }&&& public long getCreateDate() {
&&&&&&& return createD
&&& }&&& public void setCreateDate(long createDate) {
&&&&&&& this.createDate = createD
&&& }&&& public long getUpdateDate() {
&&&&&&& return updateD
&&& }&&& public void setUpdateDate(long updateDate) {
&&&&&&& this.updateDate = updateD
&&& }&&& public Bill getReferBill() {
&&&&&&& return referB
&&& }&&& public void setReferBill(Bill referBill) {
&&&&&&& this.referBill = referB
&&& }}然后建立自己的daopublic class CashFlowDao extends BaseDao&CashFlow, Integer& {&public CashFlowDao(Context context) {
&&super(context);
&}&@Override
&public Dao&CashFlow, Integer& getDao() throws SQLException {
&&return getHelper().getDao(CashFlow.class);
&}}最后应用dao,查询某一段时间内的CashFlow&@SuppressWarnings(&deprecation&)
&&& private void queCashFlow(int msgType, long lowTime, long highTime) {
&&&&&&& try {
&&&&&&&&&&& CashFlowDao cashFlowDao = new CashFlowDao(this);
&&&&&&&&&&& Map&String, Object& map = new HashMap&String, Object&();
&&&&&&&&&&& Map&String, Object& lowMap = new HashMap&String, Object&();
&&&&&&&&&&& lowMap.put(&create_date&, lowTime);
&&&&&&&&&&& Map&String, Object& highMap = new HashMap&String, Object&();
&&&&&&&&&&& highMap.put(&create_date&, highTime);
&&&&&&&&&&& ArrayList&CashFlow& cashFlows = (ArrayList&CashFlow&)cashFlowDao.query(map, lowMap,
&&&&&&&&&&&&&&&&&&& highMap);
&&&&&&&&&&& if (cashFlows != null && cashFlows.size() & 0) {
&&&&&&&&&&&&&&& Message message = new Message();
&&&&&&&&&&&&&&& message.what = msgT
&&&&&&&&&&&&&&& message.obj = cashF
&&&&&&&&&&&&&&& handler.sendMessage(message);
&&&&&&&&&&& } else {
&&&&&&&&&&&&&&& handler.sendEmptyMessage(4);
&&&&&&&&&&& }
&&&&&&& } catch (SQLException e) {
&&&&&&&&&&& handler.sendEmptyMessage(4);
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:420023次
积分:3208
积分:3208
排名:第8089名
原创:48篇
评论:104条
(1)(1)(1)(2)(1)(1)(2)(1)(3)(1)(20)(14)&#xe621; 上传我的文档
&#xe602; 下载
&#xe60c; 收藏
本人资料一部分是自己原创,一部分来源于网络,若您发现侵犯您个人权利的,请留言联系我,我立马删除。
&#xe602; 下载此文档
正在努力加载中...
基于Android的多功能日程表系统的设计与实现
下载积分:2000
内容提示:基于Android的多功能日程表系统的设计与实现
文档格式:DOC|
浏览次数:5|
上传日期: 20:13:52|
文档星级:&#xe60b;&#xe612;&#xe612;&#xe612;&#xe612;
该用户还上传了这些文档
基于Android的多功能日程表系统的设计与实现
官方公共微信<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
您的访问请求被拒绝 403 Forbidden - ITeye技术社区
您的访问请求被拒绝
亲爱的会员,您的IP地址所在网段被ITeye拒绝服务,这可能是以下两种情况导致:
一、您所在的网段内有网络爬虫大量抓取ITeye网页,为保证其他人流畅的访问ITeye,该网段被ITeye拒绝
二、您通过某个代理服务器访问ITeye网站,该代理服务器被网络爬虫利用,大量抓取ITeye网页
请您点击按钮解除封锁&81545人阅读
【Android 快速开发】(11)
【android 进阶之路】(68)
转载请标明出处:,本文出自【张鸿洋的博客】上一篇已经对ORMLite框架做了简单的介绍:~~本篇将介绍项目可能会使用到的一些用法,也为我们的使用ORMLite框架总结出一个较合理的用法。通过上一篇的了解,我们使用ORMLite,需要自己写一个DatabaseHelper去继承OrmLiteSqliteOpenHelper,下面我们首先给出一个我认为比较靠谱的Helper的写法:1、DatabaseHelperpackage com.zhy.zhy_ormlite.
import java.sql.SQLE
import java.util.HashM
import java.util.M
import android.content.C
import android.database.sqlite.SQLiteD
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenH
import com.j256.ormlite.dao.D
import com.j256.ormlite.support.ConnectionS
import com.j256.ormlite.table.TableU
import com.zhy.zhy_ormlite.bean.A
import com.zhy.zhy_ormlite.bean.S
import com.zhy.zhy_ormlite.bean.U
class DatabaseHelper extends OrmLiteSqliteOpenHelper
private static final String TABLE_NAME = &sqlite-test.db&;
private Map&String, Dao& daos = new HashMap&String, Dao&();
private DatabaseHelper(Context context)
super(context, TABLE_NAME, null, 4);
public void onCreate(SQLiteDatabase database,
ConnectionSource connectionSource)
TableUtils.createTable(connectionSource, User.class);
TableUtils.createTable(connectionSource, Article.class);
TableUtils.createTable(connectionSource, Student.class);
} catch (SQLException e)
e.printStackTrace();
public void onUpgrade(SQLiteDatabase database,
ConnectionSource connectionSource, int oldVersion, int newVersion)
TableUtils.dropTable(connectionSource, User.class, true);
TableUtils.dropTable(connectionSource, Article.class, true);
TableUtils.dropTable(connectionSource, Student.class, true);
onCreate(database, connectionSource);
} catch (SQLException e)
e.printStackTrace();
private static DatabaseH
* 单例获取该Helper
* @param context
public static synchronized DatabaseHelper getHelper(Context context)
context = context.getApplicationContext();
if (instance == null)
synchronized (DatabaseHelper.class)
if (instance == null)
instance = new DatabaseHelper(context);
public synchronized Dao getDao(Class clazz) throws SQLException
String className = clazz.getSimpleName();
if (daos.containsKey(className))
dao = daos.get(className);
if (dao == null)
dao = super.getDao(clazz);
daos.put(className, dao);
* 释放资源
public void close()
super.close();
for (String key : daos.keySet())
Dao dao = daos.get(key);
1、整个DatabaseHelper使用单例只对外公布出一个对象,保证app中只存在一个SQLite Connection , 参考文章:http://www.touchlab.co/2011/10/single-sqlite-connection/2、我们对每个Bean创建一个XXXDao来处理当前Bean的数据库操作,当然真正去和数据库打交道的对象,通过上面代码中的getDao(T t)进行获取getDao为一个泛型方法,会根据传入Class对象进行创建Dao,并且使用一个Map来保持所有的Dao对象,只有第一次调用时才会去调用底层的getDao()。2、Bean的Daopackage com.zhy.zhy_ormlite.
import java.sql.SQLE
import android.content.C
import com.j256.ormlite.dao.D
import com.zhy.zhy_ormlite.bean.U
public class UserDao
private Dao&User, Integer& userDaoO
private DatabaseH
public UserDao(Context context)
this.context =
helper = DatabaseHelper.getHelper(context);
userDaoOpe = helper.getDao(User.class);
} catch (SQLException e)
e.printStackTrace();
* 增加一个用户
* @param user
public void add(User user)
userDaoOpe.create(user);
} catch (SQLException e)
e.printStackTrace();
}//...other operations
我们的所有的XXXDao遵循以上的风格~好了,基本了解了我们的代码的结构~~ps:如果觉得不合理可以留言指出,如果觉得不能接收,直接忽略。。。3、ORMLite外键引用现在我们有两张表一张User,一张Article;&Article中当然需要存储User的主键,作为关联~~那么在ORMLite中如何做到呢?可能有人会直接在Article中声明一个int类型userId属性,当作普通属性处理搞定,这种做法并没有做,但是没有体现出面向对象的思想。面向对象是这样的:Article属于某个User类这么定义:package com.zhy.zhy_ormlite.
import com.j256.ormlite.field.DatabaseF
import com.j256.ormlite.table.DatabaseT
@DatabaseTable(tableName = &tb_article&)
public class Article
@DatabaseField(generatedId = true)
@DatabaseField
@DatabaseField(canBeNull = true, foreign = true, columnName = &user_id&)
public int getId()
public void setId(int id)
public String getTitle()
public void setTitle(String title)
this.title =
public User getUser()
public void setUser(User user)
this.user =
public String toString()
return &Article [id=& + id + &, title=& + title + &, user=& + user
不会去定义一个int类型的userId,而是直接定义一个User成员变量,表示本Article属于该U然后在User user属性上添加: @DatabaseField(canBeNull = true, foreign = true, columnName = &user_id&)canBeNull -表示不能为null;foreign=true表示是一个外键;columnName 列名User类暂且就两个属性:package com.zhy.zhy_ormlite.
import com.j256.ormlite.field.DatabaseF
import com.j256.ormlite.table.DatabaseT
@DatabaseTable(tableName = &tb_user&)
public class User
@DatabaseField(generatedId = true)
@DatabaseField(columnName = &name&)
public User()
public int getId()
public void setId(int id)
public String getName()
public void setName(String name)
this.name =
public String toString()
return &User [id=& + id + &, name=& + name
现在看我们的ArticleDaopackage com.zhy.zhy_ormlite.
import java.sql.SQLE
import java.util.L
import android.content.C
import com.j256.ormlite.dao.D
import com.zhy.zhy_ormlite.bean.A
import com.zhy.zhy_ormlite.bean.U
public class ArticleDao
private Dao&Article, Integer& articleDaoO
private DatabaseH
@SuppressWarnings(&unchecked&)
public ArticleDao(Context context)
helper = DatabaseHelper.getHelper(context);
articleDaoOpe = helper.getDao(Article.class);
} catch (SQLException e)
e.printStackTrace();
* 添加一个Article
* @param article
public void add(Article article)
articleDaoOpe.create(article);
} catch (SQLException e)
e.printStackTrace();
* 通过Id得到一个Article
* @param id
@SuppressWarnings(&unchecked&)
public Article getArticleWithUser(int id)
Article article =
article = articleDaoOpe.queryForId(id);
helper.getDao(User.class).refresh(article.getUser());
} catch (SQLException e)
e.printStackTrace();
* 通过Id得到一篇文章
* @param id
public Article get(int id)
Article article =
article = articleDaoOpe.queryForId(id);
} catch (SQLException e)
e.printStackTrace();
* 通过UserId获取所有的文章
* @param userId
public List&Article& listByUserId(int userId)
return articleDaoOpe.queryBuilder().where().eq(&user_id&, userId)
} catch (SQLException e)
e.printStackTrace();
接下来看我们的测试类:public class OrmLiteDbTest extends AndroidTestCase
public void testAddArticle()
User u = new User();
u.setName(&张鸿洋&);
new UserDao(getContext()).add(u);
Article article = new Article();
article.setTitle(&ORMLite的使用&);
article.setUser(u);
new ArticleDao(getContext()).add(article);
public void testGetArticleById()
Article article = new ArticleDao(getContext()).get(1);
L.e(article.getUser() + & , & + article.getTitle());
public void testGetArticleWithUser()
Article article = new ArticleDao(getContext()).getArticleWithUser(1);
L.e(article.getUser() + & , & + article.getTitle());
public void testListArticlesByUserId()
List&Article& articles = new ArticleDao(getContext()).listByUserId(1);
L.e(articles.toString());
}分别测试,添加一个Article;通过Id获取一个Article;通过Id获取一个Article且携带User;通过userId获取所有的Article;主要看第三个:通过Id获取一个Article且携带User,testGetArticleWithUser(id)如何值传一个Article的Id,然后能够拿到Article对象,且内部的user属性直接赋值呢?两种方式:1、即上述写法article = articleDaoOpe.queryForId(id);
helper.getDao(User.class).refresh(article.getUser());2、在user属性的注解上:@DatabaseField(canBeNull = true, foreign = true, columnName = &user_id&, foreignAutoRefresh = true)添加foreignAutoRefresh =true,这样;当调用queryForId时,拿到Article对象则直接携带了user;4、关联一个集合每个User关联一个或多个Article,如果我在User中声明一个Collection&Article& articles,我能否在查询User的时候,一并能够获取到articles的值呢?答案是可以的。在User中添加如下属性,且注解如下:@ForeignCollectionFieldprivate Collection&Article&我们在UserDao中书写查询User的代码:public User get(int id)
return userDaoOpe.queryForId(id);
} catch (SQLException e)
e.printStackTrace();
}测试代码:public void testGetUserById()
User user = new UserDao(getContext()).get(1);
L.e(user.getName());
if (user.getArticles() != null)
for (Article article : user.getArticles())
L.e(article.toString());
}输出:09-07 22:49:06.484: E/zhy(7293): 张鸿洋
09-07 22:49:06.484: E/zhy(7293): Article [id=1, title=ORMLite的使用]
可以看到,我们通过一个queryForId,成功的获取了User,以及User关联的所有的Articles;5、条件查询QueryBuilder的使用上述代码其实已经用到了简单的条件查询了:1、简单的where等于articleDaoOpe.queryBuilder().where().eq(&user_id&, userId).query();直接返回Article的列表2、where and& QueryBuilder&Article, Integer& queryBuilder = articleDaoOpe
.queryBuilder();
Where&Article, Integer& where = queryBuilder.where();
where.eq(&user_id&, 1);
where.and();
where.eq(&name&, &xxx&);
articleDaoOpe.queryBuilder().//
where().//
eq(&user_id&, 1).and().//
eq(&name&, &xxx&);上述两种都相当与:select * from tb_article where user_id = 1 and name = 'xxx' ;&3、更复杂的查询where.or(
where.and(//
where.eq(&user_id&, 1), where.eq(&name&, &xxx&)),
where.and(//
where.eq(&user_id&, 2), where.eq(&name&, &yyy&)));select * from tb_article where ( user_id = 1 and name = 'xxx' ) &or (&user_id = 2 and name = 'yyy' )&&;好了,再复杂的查询估计也能够凑出来了~~6、updateBuilder、deleteBuilder使用queryBuilder是因为我们希望执行完成查询直接返回List&Bean&集合;对于Update我们并不关注返回值,直接使用articleDaoOpe.updateRaw(statement, arguments);传入sql和参数即可~~何必在那articleDaoOpe.updateBuilder().updateColumnValue(&name&,&zzz&).where().eq(&user_id&, 1);这样的痛苦呢~~~同理还有deleteBuilder还是建议直接拼写sql,当然很简单的除外,直接使用它的API~7、事务操作在我们的Dao中直接写如下代码://事务操作
TransactionManager.callInTransaction(helper.getConnectionSource(),
new Callable&Void&()
public Void call() throws Exception
});8、其他操作1、当Bean继承BaseDaoEnabled时,可以使用bean.create(bean);bean.update(bean)一类操作例如:Student extends BaseDaoEnabled&Student, Integer&Dao dao = DatabaseHelper.getHelper(getContext()).getDao(Student.class);Student student = new Student();student.setDao(dao);student.setName(&张鸿洋&);student.create();前提dao需要手动设置,如果dao为null会报错,尼玛,我觉得一点用没有。。。2、JoinQueryBuilder&Article, Integer& articleBuilder = articleDaoOpe
.queryBuilder();
QueryBuilder userBuilder = helper.getDao(User.class).queryBuilder();
articleBuilder.join(userBuilder);Article与User做Join操作;本篇主要想介绍在项目中如何写DataBaseHelper已经如何写BeanDao,以及列出了在项目中可能会用到的ORMLite的功能,如果需要详细了解,还请看ORMLite官方文档,源码中也会提供~~&
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
积分:43128
积分:43128
排名:第61名
原创:192篇
评论:12435条
长期为您推荐优秀博文、开源项目、视频等,进入还有好玩的等着你,欢迎扫一扫。
请勿重复加群,Thx
文章:11篇
阅读:154112
文章:10篇
阅读:91808
文章:67篇
阅读:4621281}

我要回帖

更多关于 dbtable 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信