Android使用OrmLite数据库框架 之 基本用法

来源:互联网 发布:js中数字转换大写金额 编辑:程序博客网 时间:2024/06/05 03:51

官网:http://ormlite.com/

 

官方帮助,目录:

http://ormlite.com/javadoc/ormlite-core/doc-files/ormlite_toc.html#SEC_Contents


引用:“OrmLite提供了一些轻量级持久化Java对象到SQL数据库,同时也避免了复杂性和更多的标准的ORM包的开销功能。它支持的SQL数据库使用JDBC的数量,还支持原生的Android操作系统数据库API调用sqlite。”


先说说我学习本框架的方法:

1.先从官网下Demo跑起来看效果牛不牛逼

2.用谷姐和度娘找技术贴,鸡本没神马。。。抓狂

3.看官网的英文API--这对于一个没过四级的苦逼程序员来说是什么?

4.测试


因为网上资料少,所以我整理一下学习笔记发到这里。

下面只是大概的使用方法,欲知更多,或以留言(反正我不回复)或者请看官网!

 


Demo效果艳照图:



Demo下载地址:http://download.csdn.net/detail/oo8_8oo/4096822


1.导入JAR包

2.写VO类,通过注解实现ORM。

@DatabaseTable表示该VO类对应着一张表,

@DatabaseTable(tableName = "accounts")public class Account {…

解释:Account类对应着“accounts”表,如果不配置tableName,则表名默认与VO类名相同。

@DatabaseTable(tableName= "accounts")

public class Account {@DatabaseField(id= true)    private String name;@DatabaseField(canBeNull = false)    private String password;    …

解释:name的注解表明name是accounts表中的主键,password是不能为空的字段。

一对多的实现方法:

@ForeignCollectionFieldprivate ForeignCollection<User> users;

VO类里必须得有一个无参的构造器。 

Vo可以继承BaseDaoEnabled<T,ID>类,然后就可以实现在VO里直接调用DAO的方法,如:

create()、refresh()、update()……

不过,在使用前VO必须先 setDao(Dao<T, ID> dao) 

3.编写DAO

方法如下:

Dao<Account,String> accountDao =  DaoManager.createDao(connectionSource,Account.class);Dao<Order, Integer> orderDao =  DaoManager.createDao(connectionSource,Order.class);

当然,我们可以编写一个接口,让DAO实现该接口,方法如下:

/**Account DAO which has a String id (Account.name) */public interface AccountDao extends Dao<Account, String> {    // empty wrapper, you can addadditional DAO methods here}

/** JDBCimplementation of the AccountDao interface. */public class AccountDaoImpl extends BaseDaoImpl<Account,String>  implements AccountDao {    publicAccountDaoImpl(ConnectionSource connectionSource)      throws SQLException {        super(connectionSource,Account.class);    }}

这样我们就可以在接口里加增加自己的方法。 

4.相关类

TableUtils 

TableUtils.createTable(connectionSource, Account.class);//创建Account实体类对应的表

----- 外键自动refresh 

5.另外

Activity继承OrmLiteBaseActivity,便会在onCreat()和onDestroy()方法中获得和释放DatabaseHelp。使用时只需要调用getHelper()。