一 插件简介:

其github地址:https://github.com/li6185377/LKDBHelper-SQLite-ORM

全面支持 NSArray,NSDictionary, ModelClass, NSNumber, NSString, NSDate, NSData, UIColor, UIImage, CGRect, CGPoint, CGSize, NSRange, int,char,float, double, long.. 等属性的自动化操作(插入和查询)

二 实例内容:

采用pods进行加载LKDBHelper插件,若有下载源代码调试时记得更新一下(平常项目中记得对libsqlite3.dylib进行引用);


本实例创建一个父实体BaseBean,后面其它实体都进行继承;

1:父实体的代码内容

BaseBean.h内容:

#import <Foundation/Foundation.h>
#import <LKDBHelper/LKDBHelper.h> @interface BaseBean : NSObject @end //这个NSOBJECT的扩展类 可以查看详细的建表sql语句
@interface NSObject(PrintSQL)
+(NSString*)getCreateTableSQL;
@end

*这边可以放一些其它实体都公有的属性,及lkdbhelper数据库的地址;其中PrintSQL是对NSObject的扩展,可以查看创建表的sql语句;

BaseBean.m内容:

#import "BaseBean.h"

@implementation BaseBean

+(LKDBHelper *)getUsingLKDBHelper
{
static LKDBHelper* db;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSString *sqlitePath = [BaseBean downloadPath];
NSString* dbpath = [sqlitePath stringByAppendingPathComponent:[NSString stringWithFormat:@"lkdbhelperTest.db"]];
db = [[LKDBHelper alloc]initWithDBPath:dbpath];
});
return db;
} /**
* @author wujunyang, 15-05-21 16:05:44
*
* @brief 路径
* @return <#return value description#>
*/
+ (NSString *)downloadPath{
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *downloadPath = [documentPath stringByAppendingPathComponent:@"wjy"];
NSLog(@"%@",downloadPath);
return downloadPath;
}
@end @implementation NSObject(PrintSQL) +(NSString *)getCreateTableSQL
{
LKModelInfos* infos = [self getModelInfos];
NSString* primaryKey = [self getPrimaryKey];
NSMutableString* table_pars = [NSMutableString string];
for (int i=; i<infos.count; i++) { if(i > )
[table_pars appendString:@","]; LKDBProperty* property = [infos objectWithIndex:i];
[self columnAttributeWithProperty:property]; [table_pars appendFormat:@"%@ %@",property.sqlColumnName,property.sqlColumnType]; if([property.sqlColumnType isEqualToString:LKSQL_Type_Text])
{
if(property.length>)
{
[table_pars appendFormat:@"(%ld)",(long)property.length];
}
}
if(property.isNotNull)
{
[table_pars appendFormat:@" %@",LKSQL_Attribute_NotNull];
}
if(property.isUnique)
{
[table_pars appendFormat:@" %@",LKSQL_Attribute_Unique];
}
if(property.checkValue)
{
[table_pars appendFormat:@" %@(%@)",LKSQL_Attribute_Check,property.checkValue];
}
if(property.defaultValue)
{
[table_pars appendFormat:@" %@ %@",LKSQL_Attribute_Default,property.defaultValue];
}
if(primaryKey && [property.sqlColumnName isEqualToString:primaryKey])
{
[table_pars appendFormat:@" %@",LKSQL_Attribute_PrimaryKey];
}
}
NSString* createTableSQL = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(%@)",[self getTableName],table_pars];
return createTableSQL;
} @end

2:子实体CarBean的内容,其是另外一个实体UserBean的一个外键

CarBean.h内容:

#import <Foundation/Foundation.h>
#import "BaseBean.h" @interface CarBean : BaseBean @property(assign,nonatomic)int carID;
@property(strong,nonatomic)NSString *carNum;
@property(strong,nonatomic)NSString *address;
@property(assign,nonatomic)float carWidth;
@end *注意继承BaseBean CarBean.m内容: #import "CarBean.h" @implementation CarBean +(void)initialize
{
//单个要不显示时
[self removePropertyWithColumnName:@"address"];
//多列要不显示时
//[self removePropertyWithColumnNameArray:]; //修改列对应到表时 重命名新列名
[self setTableColumnName:@"MyCarWidth" bindingPropertyName:@"carWidth"];
} /**
* @author wjy, 15-01-27 18:01:53
*
* @brief 是否将父实体类的属性也映射到sqlite库表
* @return BOOL
*/
+(BOOL) isContainParent{
return YES;
}
/**
* @author wjy, 15-01-26 14:01:01
*
* @brief 设定表名
* @return 返回表名
*/
+(NSString *)getTableName
{
return @"carbean";
}
/**
* @author wjy, 15-01-26 14:01:22
*
* @brief 设定表的单个主键
* @return 返回主键表
*/
+(NSString *)getPrimaryKey
{
return @"carID";
} /////复合主键 这个优先级最高
//+(NSArray *)getPrimaryKeyUnionArray
//{
// return @[@"carID",@"carNum"];
//} @end

*主要注意关于可以把一些属性过滤掉,就不会创建到表中,也可以对列名进行重定义,其它几个代码有详细说明

3:子实体UserBean,同样继承BaseBean

UserBean.h内容:

#import <Foundation/Foundation.h>
#import "BaseBean.h"
#import "CarBean.h" @interface UserBean : BaseBean @property(assign,nonatomic)int ID;
@property(strong,nonatomic)NSString *userName;
@property(strong,nonatomic)NSString *password;
@property(assign,nonatomic)int age; @property(strong,nonatomic)CarBean *myCar;
@end UserBean.m内容: #import "UserBean.h" @implementation UserBean +(void)initialize
{
[self removePropertyWithColumnName:@"error"];
} /**
* @author wjy, 15-01-27 18:01:53
*
* @brief 是否将父实体类的属性也映射到sqlite库表
* @return BOOL
*/
+(BOOL) isContainParent{
return YES;
}
/**
* @author wjy, 15-01-26 14:01:01
*
* @brief 设定表名
* @return 返回表名
*/
+(NSString *)getTableName
{
return @"userBean";
}
/**
* @author wjy, 15-01-26 14:01:22
*
* @brief 设定表的单个主键
* @return 返回主键表
*/
+(NSString *)getPrimaryKey
{
return @"ID";
}
@end

4:开始进行针对数据库进行操作

4.1 功能包括删除所有表,清理指定表的数据,创建表插入数据,其中插入数据会自动判断表是否存在,若不存在则先创建表再插入,特别说明就是当一个列被定义为int且是主键时,它要是没有被赋值就会自动增长

    LKDBHelper* globalHelper = [BaseBean getUsingLKDBHelper];

    //删除所有的表
[globalHelper dropAllTable]; //清理所有数据
[LKDBHelper clearTableData:[UserBean class]]; UserBean *user=[[UserBean alloc] init];
//user.ID=1000; //特别说明 如果是主键 没给它赋值它就会自动增长
user.userName=@"WUJY";
user.password=@"";
user.age=; CarBean *car=[[CarBean alloc]init];
car.carNum=@"D88888";
car.address=@"厦门软件园";
car.carWidth=12.5; user.myCar=car; //插入数据 如果表不存在 它会自动创建再插入 实体实例化LKDBHelper 若是继承记得引用 否则会没有效果
[user saveToDB]; //另外一种插入
user.age=;
[globalHelper insertToDB:user];

4.2 关于事务的操作

    //事物  transaction 这边故意让它插入失败
[globalHelper executeForTransaction:^BOOL(LKDBHelper *helper) { user.ID = ;
user.userName=@"wujy10";
BOOL success = [helper insertToDB:user]; user.ID = ;
user.userName=@"wujy09";
success = [helper insertToDB:user]; //重复主键
user.ID = ;
BOOL insertSucceed = [helper insertWhenNotExists:user]; //insert fail
if(insertSucceed == NO)
{
///rollback
return NO;
}
else
{
///commit
return YES;
}
}];

4.3 关于异步操作,对于其它操作也同样支持异步操作,采用callback方式进行回调

    user.userName=@"异步";
[globalHelper insertToDB:user callback:^(BOOL result) {
NSLog(@"异步插入是否成功:%@",result>?@"是":@"否");
}]; //异步查询
[globalHelper search:[UserBean class] where:nil orderBy:nil offset: count: callback:^(NSMutableArray *array) {
for (id obj in array) {
NSLog(@"异步:%@",[obj printAllPropertys]);
}
}];

4.4 关于查询功能的几种操作,特别注意条件的写法,其它在代码中有相应的注解;

    NSMutableArray* searchResultArray=nil;

    //同步搜索 执行sql语句 把结果再变成对象
searchResultArray=[globalHelper searchWithSQL:@"select * from @t" toClass:[UserBean class]];
for (id obj in searchResultArray) {
NSLog(@"sql语句:%@",[obj printAllPropertys]);
} //使用对象对进查询操作 offset是跳过多少行 count是查询多少条
searchResultArray=[UserBean searchWithWhere:nil orderBy:nil offset: count:];
for (id obj in searchResultArray) {
NSLog(@"实体:%@",[obj printAllPropertys]);
} //查询一列时的操作 count为0时则查所有列
NSArray* nameArray = [UserBean searchColumn:@"userName" where:nil orderBy:nil offset: count:];
NSLog(@"%@",[nameArray componentsJoinedByString:@","]); //查询多列时的操作
NSArray* twoColumn=[UserBean searchColumn:@"ID,userName" where:nil orderBy:nil offset: count:];
for (UserBean *obj in twoColumn) {
NSLog(@"%d-%@",obj.ID,obj.userName);
} //组合查询四种 and or like in
searchResultArray=[UserBean searchWithWhere:[NSString stringWithFormat:@"userName like '%%JY%%'"] orderBy:nil offset: count:];
NSLog(@"LIKE :%lu",searchResultArray.count); searchResultArray=[UserBean searchWithWhere:[NSString stringWithFormat:@"age=29 and userName='WUJY'"] orderBy:nil offset: count:];
NSLog(@"AND :%lu",searchResultArray.count); searchResultArray=[globalHelper search:[UserBean class] where:@{@"age":@,@"userName":@"WUJY"} orderBy:nil offset: count:];
NSLog(@"AND %lu",searchResultArray.count); searchResultArray=[UserBean searchWithWhere:[NSString stringWithFormat:@"age=29 or userName='WUJY'"] orderBy:nil offset: count:];
NSLog(@"OR %lu",searchResultArray.count); searchResultArray=[UserBean searchWithWhere:[NSString stringWithFormat:@"age in (10,29)"] orderBy:nil offset: count:];
NSLog(@"in %lu",searchResultArray.count); searchResultArray=[globalHelper search:[UserBean class] where:@{@"age":@[@,@]} orderBy:nil offset: count:];
NSLog(@"in %lu",searchResultArray.count); //查询符合条件的条数
NSInteger rowCount=[UserBean rowCountWithWhere:@"age=29"];
NSLog(@"rowCount %ld",rowCount);
*注意:

单条件:
@"rowid = 1" 或者 @{@"rowid":@} 多条件:
@“rowid = and sex = " 或者 @{@"rowid":@1,@"sex":@0}
如果是or类型的条件,则只能用字符串的形式:@"rowid = 1 or sex = 0" in条件:
@"rowid in (1,2,3)" 或者 @{@"rowid":@[@,@,@]}
多条件带in:@"rowid in (1,2,3) and sex=0 " 或者 @{@"rowid":@[@,@,@],@"sex":@} 时间也只能用字符串:
@"date >= '2013-04-01 00:00:00'" like也只能用字符串:
@"userName like '%%JY%%'"

4.5 更新操作

    //带条件更新
user.userName=@"踏浪帅";
BOOL isUpDate=[globalHelper updateToDB:user where:@{@"ID":@}];
NSLog(@"是否更新成功:%@",isUpDate>?@"是":@"否"); //根据条件获得后进行更新
searchResultArray=[UserBean searchWithWhere:[NSString stringWithFormat:@"userName='%@'",@"WUJY"] orderBy:nil offset: count:];
user=[searchResultArray firstObject];
user.password=@"aa123456";
BOOL moreUpdate=[globalHelper updateToDB:user where:nil];
NSLog(@"根据条件获得后进行更新:%@",moreUpdate>?@"是":@"否"); //更新 访问表名 更新内容跟条件进行更新
BOOL updateTab=[globalHelper updateToDBWithTableName:@"userBean" set:@"password='aa123456'" where:@"age=10"];
NSLog(@"访问表名更新内容跟条件进行更新:%@",updateTab>?@"是":@"否"); //根据 实类进行更新
BOOL updateClass=[globalHelper updateToDB:[UserBean class] set:@"password='cnblogs'" where:@"userName='WUJY'"];
NSLog(@"根据实类进行更新:%@",updateClass>?@"是":@"否");

4.6 删除操作

    //删除功能
user=[globalHelper searchSingle:[UserBean class] where:@{@"age":@} orderBy:nil];
BOOL ishas=[globalHelper isExistsModel:user];
if (ishas) {
[globalHelper deleteToDB:user];
} //删除多条
BOOL isDeleteMore=[globalHelper deleteWithClass:[UserBean class] where:@"age=29"];
if (isDeleteMore) {
NSLog(@"符合条件的都被删除");
}

提供本代码下载地址(本实例只是本人练习,若有问题望指正):源代码下载

IOS关于LKDBHelper实体对象映射插件运用的更多相关文章

  1. iOS:LKDBHelper实体对象映射数据库-第三方框架(在FMDB的基础上进行二次封装)

    一 插件简介: 其github地址:https://github.com/li6185377/LKDBHelper-SQLite-ORM 全面支持 NSArray,NSDictionary, Mode ...

  2. 无线客户端框架设计(5.1):将JSON映射为实体对象(iOS篇)

    iOS开发人员已经习惯于将JSON转换为字典或者数组来进行操作了,接下来我要做的事情,可能匪夷所思,但是,对WP和Android开发人员而言,他们更倾向于将JSON转换为实体对象进行操作. 我所设计的 ...

  3. 将JSON映射为实体对象(iOS篇)

    将JSON映射为实体对象(iOS篇) iOS开发人员已经习惯于将JSON转换为字典或者数组来进行操作了,接下来我要做的事情,可能匪夷所思,但是,对WP和Android开发人员而言,他们更倾向于将JSO ...

  4. mybatis-generator 动态生成实体对象、dao 以及相关的xml映射文件

    .新建maven空项目 2.修改pom.xml文件 <?xml version="1.0" encoding="UTF-8"?> <proje ...

  5. EF架构~AutoMapper对象映射工具简化了实体赋值的过程

    回到目录 AutoMapper是一个.NET的对象映射工具,一般地,我们进行面向服务的开发时,都会涉及到DTO的概念,即数据传输对象,而为了减少系统的负载,一般我们不会把整个表的字段作为传输的数据,而 ...

  6. Java实战之02Hibernate-02映射、一级缓存、实体对象状态

    五.映射基础 1.实体类采用javabean的编写规范 JavaBean编写规范: a.类一般是public的 b.有默认的构造方法 c.字段都是私有的 d.提供公有的getter和setter方法 ...

  7. 一行code实现ADO.NET查询结果映射至实体对象。

    AutoMapper是一个.NET的对象映射工具. 主要用途 领域对象与DTO之间的转换.数据库查询结果映射至实体对象. 这次我们说说 数据库查询结果映射至实体对象. 先贴一段代码: public S ...

  8. Activiti 5.17 实体对象与类和数据库表的映射

    一.Activiti 5.17 mybatis的mapping文件声明映射的实体对象关系. <configuration><settings><settingname=& ...

  9. ASP.NET Core搭建多层网站架构【8.2-使用AutoMapper映射实体对象】

    2020/01/29, ASP.NET Core 3.1, VS2019, AutoMapper.Extensions.Microsoft.DependencyInjection 7.0.0 摘要:基 ...

随机推荐

  1. border-radius四个值的问题

    我们都知道border-radius后面如果是4个值的话,依次代表的是左上角.右上角.右下角.左下角. 但是这样写呢:border-radius:10px 20px 30px 40px/50px 40 ...

  2. Vue - 在v-repeat中使用计算属性

    1.从后端获取JSON数据集合后,对单条数据应用计算属性,在Vue.js 0.12版本之前可以在v-repeat所在元素上使用v-component指令 在Vue.js 0.12版本之后使用自定义元素 ...

  3. 学习android 官方文档

    9.29 1. 今天,FQ,看到android studio中文网上有一个FQ工具openVPN,我就使用了. 之前用过一个FQ工具开眼,但由于网速慢,我就弃用了. 2. 现在,我就可以FQ去andr ...

  4. Ajax跨域问题的两种解决方法

    浏览器不允许Ajax跨站请求,所以存在Ajax跨域问题,目前主要有两种办法解决. 1.在请求页面上使用Access-Control-Allow-Origin标头. 使用如下标头可以接受全部网站请求: ...

  5. haha2

    # YOU - fhasd - fdks jf > jd sfkjd sf ```python print "helloworld" ``` 来自为知笔记(Wiz)

  6. MySQL多表查询

    第一种: select a.a1,a.a2,a.a3,b.b2,c.c2,d.d2 from a,b,c,d where a.a1=b.b1 and b.b1=c.c1 and c.c1=d.d1 第 ...

  7. [译]App Framework 2.1 (1)之 Quickstart

    最近有移动App项目,选择了 Hybrid 的框架Cordova  和  App Framework 框架开发. 本来应该从配置循序渐进开始写的,但由于上班时间太忙,这段时间抽不出空来,只能根据心情和 ...

  8. 软件工程:Wordcount程序作业

    由于时间的关系,急着交作业,加上这一次也不是那么很认真的去做,草草写了“Wordcount程序”几个功能,即是 .txt文件的读取,能计算出文件内容的单词数,文件内容的字符数,及行数. 这次选用C来做 ...

  9. 在linux下Ant的环境配置

    Ant(英文全称为another neat tool,另一个简洁的工具)是一个基于Java的生成工具,Ant将会被应用到Java项目中. 同样的,现在要来安装Ant(最近要安装的东西还蛮多的=m=), ...

  10. JavaMail和James的秘密花园

    JavaMail,顾名思义,提供给开发者处理电子邮件相关的编程接口.它是Sun发布的用来处理email的API.它可以方便地执行一些常用的邮件传输.我们可以基于JavaMail开发出类似于Micros ...