当前位置:Gxlcms > 数据库问题 > LKDBHelper-ORM框架

LKDBHelper-ORM框架

时间:2021-07-01 10:21:17 帮助过:4人阅读

实现对象数据映射。其框架库在github上能找到。以下代码将通过LKDBHelper实现增删查改。

1 实现数据对应的Bean对象,以下提供.h文件。

#import <Foundation/Foundation.h>

@interface WBUser : NSObject

@property (nonatomic,copy) NSString *userName;

@property (nonatomic,assign) int age;

@end

2 提供实现的Dao层。

WBUserDao.h

#import <Foundation/Foundation.h>
#import "WBUser.h"

@interface WBUserDao : NSObject

+(instancetype)daoWithEntityClass:(Class)aclass;

-(void)saveUser:(WBUser *)user;

-(WBUser *)loadUserWithWherecase:(NSString *)where;

-(BOOL)updateUserWithWherecase:(NSString *)where;

-(void)deleteWithWherecase:(NSString *)where;

@end

WBUserDao.m

#import "WBUserDao.h"
#import "LKDBHelper.h"

@interface WBUserDao ()

@property (nonatomic,strong) Class entityClass;
@property (nonatomic,strong) LKDBHelper *gobalHelper;

@end

@implementation WBUserDao

+(instancetype)daoWithEntityClass:(Class)aclass
{
    WBUserDao *dao=[[[self class] alloc] initWithEntityClass:aclass];
    return dao;
}

-(instancetype)initWithEntityClass:(Class)aclass
{
    if (self=[super init]) {
        _entityClass=aclass;
        _gobalHelper=[LKDBHelper getUsingLKDBHelper];
        [_gobalHelper createTableWithModelClass:[_entityClass class]];
    }
    return self;
}

-(void)saveUser:(WBUser *)user
{
    NSLog(@"%d",[_gobalHelper insertToDB:user]);
}

-(WBUser *)loadUserWithWherecase:(NSString *)where
{
    return [_gobalHelper searchSingle:[WBUser class] where:where orderBy:nil];
}

-(BOOL)updateUserWithWherecase:(NSString *)where
{
    return [_gobalHelper updateToDB:[WBUser class] set:@"age = 15 " where:where];
}

-(void)deleteWithWherecase:(NSString *)where
{
    [_gobalHelper deleteWithClass:[WBUser class] where:where callback:^(BOOL result) {
        NSLog(@"delete result :%d",result);
    }];
}

@end

3 以下代码显示如何调用。我们在ViewDidLoad中实现

- (void)viewDidLoad {
    [super viewDidLoad];
    
    WBUser *user=[[WBUser alloc] init];
    user.userName=@"awdawda";
    user.age=18;
    
    WBUserDao *dao=[WBUserDao daoWithEntityClass:[user class]];
    [dao saveUser:user];
    
    WBUser *userData=[dao loadUserWithWherecase:@"userName='awdawda'"];
    
    BOOL updateFlag=[dao updateUserWithWherecase:@"userName='awdawda'"];
    
    WBUser *userData2=[dao loadUserWithWherecase:@"userName='awdawda'"];
    
    NSLog(@"%d  %d",updateFlag,userData2.age);
    
    [dao deleteWithWherecase:@"userName='awdawda'"];
    
}

Tip:在增删查改中,LKDBhelper实现的方式还有很多很多。具体看需求。gitHub:点击打开链接



LKDBHelper-ORM框架

标签:

人气教程排行