The dao implementation code and iosdao Layer Code in iOS
What is the code for the dao layer in iOS?
DAO (Data Access Object) is an Object-oriented interface. directly operate on the database, and provide data services for the business logic layer or presentation layer for adding, deleting, modifying, and searching data.
An example of dao
-(Void) saveRemind :( RemindEntity *) remind; // save a reminder-(void) deleteRemindWithWhere :( NSString *) where; // delete a reminder-(RemindEntity *) loadRemindWithRemindID :( NSString *) rid; // read a reminder-(void) deleteRemindWithRemindID :( NSString *) rid; // delete a reminder-(void) deleteremindwithwei#id :( NSString *) weistmid rcdId :( int) rcdId; // delete a contact or micro-Talk friend's reminder-(NSArray *) searchRemindWithWhere :( NSString *) where order :( NSString *) order limit :( NSString *) limit; // search reminder-(NSInteger) remindCountWithWhere :( NSString *) where; // returns the number of reminders-(NSArray *) allArrivalReminds; // returns all unexpired, reminder with the next start time less than the current time-(NSArray *) allNonOverdueReminds; // return all unexpired reminders + (void) setupDB; // initialize the database
The internal implementation uses fmdb to write a large number of SQL statements. If we have multiple entity classes, we have to write multiple dao statements.
Standardized dao
Let's take a look at a standardized dao, so you don't need to write SQL for each entity. You can inherit this class or write a factory class when using it.
@ Protocol XYBaseDaoEntityProtocol <NSObject> @ required // return table name + (NSString *) getTableName; // return primary key + (NSString *) getPrimaryKey; @ end // localized dao Class @ interface XYBaseDao: NSObject @ property (nonatomic, weak, readonly) Class entityClass; + (instancetype) daoWithEntityClass :( Class) aClass; -(NSError *) saveEntity :( id) entity;-(NSError *) saveEntityWithArray :( NSArray *) array;-(id) loadEntityWithKey :( NSString *) key;-(NSArray *) loadEntityWithWhere :( NSString *) where;-(NSInteger) countWithWhere :( NSString *) where;-(NSError *) deleteEntityWithKey :( NSString *) key;-(NSError *) deleteEntityWithWhere :( NSString *) where;-(void) deleteAllEntity; @ end
This dao is based on LKDBHelper and transmits the class of the object as the initialization parameter.
+ (Instancetype) usage :( Class) aClass {XYBaseDao * dao = [[self class] alloc] initWithEntityClass: aClass]; return dao;}-(instancetype) initWithEntityClass :( Class) aClass {self = [super init]; if (self) {_ entityClass = aClass; _ globalHelper = [LKDBHelper getUsingLKDBHelper]; // create a table [_ globalHelper createTableWithModelClass: [_ entityClass class];} return self ;}
- (NSError *)saveEntity:(id)entity{ if (entity == nil) return [NSError errorWithDomain:[NSString stringWithFormat:@"[save error] :%@", entity] code:XYBaseDao_error_code userInfo:nil]; LKDBHelper *globalHelper = [LKDBHelper getUsingLKDBHelper]; if (![globalHelper insertToDB:entity]) { return [NSError errorWithDomain:[NSString stringWithFormat:@"[save error] :%@", entity] code:XYBaseDao_error_code userInfo:nil]; } return nil;}
-(NSError *) saveEntityWithArray :( NSArray *) array {if (array = nil | array. count = 0) return [NSError errorWithDomain: [NSString stringWithFormat: @ "[save error]: % @", array] code: XYBaseDao_error_code userInfo: nil]; NSMutableString * str = [NSMutableString stringWithFormat: @ "[save error]:"]; NSInteger length = str. length; _ weak _ typeof (XYBaseDao *) weakSelf = self; // transaction [_ globalHelp Er executeDB: ^ (FMDatabase * db) {[db beginTransaction]; for (NSObject * entity in array) {if (! [WeakSelf. globalHelper insertToDB: entity]) {[str stringByAppendingFormat: @ "% @", entity] ;}} [db commit] ;}]; if (str. length> length) {return [NSError errorWithDomain: str code: XYBaseDao_error_code userInfo: nil] ;}return nil ;}
-(Id) loadEntityWithKey :( NSString *) key {if (key. length = 0) return nil; id object = [[_ entityClass alloc] init]; NSString * where = nil; if ([key isKindOfClass: [NSString class]) {where = [NSString stringWithFormat: @ "% @ = '% @'", [_ entityClass getPrimaryKey], key];} else if ([key isKindOfClass: [NSNumber class]) {where = [NSString stringWithFormat: @ "% @ = % @", [_ entityClass getPrimaryKey], key];} else if (1) {# pragma mark-todo multi-primary key type judgment where = @ "";} object = [_ entityClass searchSingleWithWhere: where orderBy: nil]; return object ;}
- (NSArray *)loadEntityWithWhere:(NSString *)where{ if (where.length == 0) return nil; NSArray *array = [_entityClass searchWithWhere:where orderBy:nil offset:0 count:XYBaseDao_load_maxCount]; return array;}
- (NSInteger)countWithWhere:(NSString *)where{ return [_entityClass rowCountWithWhere:where];}
- (NSError *)deleteEntityWithKey:(NSString *)key{ id object = [[_entityClass alloc] init]; [object setValue:key forKey:[_entityClass getPrimaryKey]]; if (![object deleteToDB]) { return [NSError errorWithDomain:[NSString stringWithFormat:@"[delete error] : %@ %@", _entityClass, key] code:XYBaseDao_error_code userInfo:nil]; } return nil;}
- (NSError *)deleteEntityWithWhere:(NSString *)where{ if (![_entityClass deleteWithWhere:where]) { return [NSError errorWithDomain:[NSString stringWithFormat:@"[delete error] : %@ %@", _entityClass, where] code:XYBaseDao_error_code userInfo:nil]; } return nil;}
- (void)deleteAllEntity{ [LKDBHelper clearTableData:[_entityClass class]];}
Demo
-(Void) clickTestDao :( id) sender {XYBaseDao * dao = [XYBaseDao daoWithEntityClass: [CarEntity class]; [dao deleteAllEntity]; carEntity * car = [[CarEntity alloc] init]; car. name = @ "a"; car. brand = @ "Cruz"; car. time = 1; [dao saveEntity: car]; CarEntity * car2 = [[CarEntity alloc] init]; car2.name = @ "B"; car2.brand = @ "Cruz "; car2.time = 1; CarEntity * car3 = [[CarEntity alloc] init]; car3.name = @ "c"; car3.brand = @ "Fox"; car3.time = 1; carEntity * car5 = [[CarEntity alloc] init]; car5.name = @ "d"; car5.brand = @ "golf"; car5.time = 1; NSArray * array = @ [car2, car3, car5]; [dao saveEntityWithArray: array]; CarEntity * car4 = [dao loadEntityWithKey: @ "c"]; NSLog (@ "% @", car4 ); NSArray * array2 = [dao loadEntityWithWhere: @ "brand = 'cruz'"]; NSLog (@ "% @", array2); NSInteger count = [dao countWithWhere: nil]; NSLog (@ "% d", count); [dao deleteEntityWithKey: @ "c"]; [dao deleteEntityWithKey: @ "brand = 'cruz'"];}
[DAO layer] explanation of java code line by line
You should use ibatis, where batch deletion is used, which is equivalent to committing a bunch of operations with one transaction to improve database performance.
// Function to delete records of all elements in the list in the database.
Protected void batchDelete (List <?> Lst, String statement)
Throws SQLException
{
GetSqlMapClient (). startBatch (); // start batch operation
// Traverse the list
For (Iterator localIterator = lst. iterator (); localIterator. hasNext ();)
{
Object obj = localIterator. next ();
GetSqlMapClient (). delete (statement, obj); // statement indicates the deletion method you call, which is defined in the xml file.
}
Getsqlmapclient(cmd.exe cuteBatch (); // end the batch operation
}
Explanation of dao-layer encapsulation code
Take the first parameter type of the generic type of the current class. Generally, the specific DAO implementation class corresponds to an entity class, which simplifies type conversion, that is, what generic type is set for your implementation class, then the corresponding methods in the class will accept what kind of parameters
For example, void insert (T t); here T is what you implement class, and here we accept what