SlideShare a Scribd company logo
1 of 21
Download to read offline
ORMLite Android
by andyang
About me
• 哲偉、Andy 、⼩小⽺羊
• Android Code Club
• Every Wed. 19:00 - 22:00 果⼦子咖啡
• Android third-party gitbook
• Join us
• Android Developer
為何我今天在這
聖亞:我報名這次的主題了
我:很好啊
聖亞:我順便幫你報了
OS:WTF
我:!!!
就這樣被推坑了,參加讀書會好處多多
可練就⼀一⾝身隨時被推坑的技能
豪華ORM就此誕⽣生
彥彬表⽰示....
有⼈人沒有使⽤用過ORM嗎?
有何不同?
進⼊入正題
使⽤用 ORMLite
製作⼀一對多資料關聯
Data Table User
@DatabaseTable(tableName = "User")
public class User {
@DatabaseField(generatedId = true)
private int id;
@DatabaseField
private String name;
@DatabaseField
private int sort;
@ForeignCollectionField
private ForeignCollection<Group> groups;
public User() {}
}
Data Table Group
@DatabaseTable(tableName = "Group")
public class Group {
@DatabaseField(generatedId = true)
private int id;
@DatabaseField
private String name;
@DatabaseField
private String description;
@DatabaseField(foreign = true, foreignAutoRefresh =
true, canBeNull = false, columnName = "user_id")
private User user;
public Group() {}
}
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Demo";
private static DatabaseHelper instance;
private DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static synchronized DatabaseHelper getHelper(Context context) {
context = context.getApplicationContext();
if (instance == null) {
synchronized (DatabaseHelper.class) {
if (instance == null)
instance = new DatabaseHelper(context);
}
}
return instance;
}
}
DatabaseHelper
onCreate & onUpdate
@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource
connectionSource, int oldVersion, int newVersion) {
try {
TableUtils.dropTable(connectionSource, User.class, true);
TableUtils.dropTable(connectionSource, Group.class, true);
onCreate(database, connectionSource);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource
connectionSource) {
try {
TableUtils.createTable(connectionSource, User.class);
TableUtils.createTable(connectionSource, Group.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
Abstract Base Dao
public abstract class BaseDao<T, ID> {
private Dao<T, ID> dao;
private DatabaseHelper helper;
public BaseDao(Context context, Class<T> clazz) {
try {
helper = DatabaseHelper.getHelper(context);
dao = helper.getDao(clazz);
} catch (SQLException e) {
e.printStackTrace();
}
}
public Dao<T, ID> getDao() {
return dao;
}
}
CRUD
public int insert(T item) {
int id;
try {
id = dao.create(item);
} catch (SQLException e) {
e.printStackTrace();
id = -1;
}
return id;
}
public int deleteById(ID primaryKey) {
int id;
try {
id = dao.deleteById(primaryKey);
} catch (SQLException e) {
e.printStackTrace();
id = -1;
}
return id;
}
public int update(T item) {
int id;
try {
id = dao.update(item);
} catch (SQLException e) {
e.printStackTrace();
id = -1;
}
return id;
}
public T getById(ID id) {
try {
return dao.queryForId(id);
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
getAll, max, minpublic List<T> getAll() {
try {
return dao.queryBuilder().orderBy("id", false).query();
} catch (SQLException e) {
e.printStackTrace();
return Collections.emptyList();
}
}
public List<T> getAll(boolean isAsc) {
try {
return dao.queryBuilder().orderBy("id", isAsc).query();
} catch (SQLException e) {
e.printStackTrace();
return Collections.emptyList();
}
}
public List<T> getAll(String field, boolean isAsc) {
try {
return dao.queryBuilder().orderBy(field, isAsc).query();
} catch (SQLException e) {
e.printStackTrace();
return Collections.emptyList();
}
}
public T maxOfFieldItem(String field) throws Exception {
return dao.queryBuilder().orderBy(field, false).limit(1L).query().get(0);
}
public T minOfFieldItem(String field) throws Exception {
return dao.queryBuilder().orderBy(field, true).limit(1L).query().get(0);
}
Transaction
public void insertWithTransaction(final List<T> items) {
try {
TransactionManager.callInTransaction(helper.getConnectionSource(),
new Callable<Void>() {
@Override
public Void call() throws Exception {
for (T t : items) {
dao.create(t);
}
return null;
}
});
} catch (SQLException e) {
e.printStackTrace();
}
}
Custom Dao
public class UserDao extends BaseDao<User, Integer>{
public UserDao(Context context) {
super(context, User.class);
}
public void swap(int sourceId, int targetId) {
int sourceSort = getById(sourceId).getSort();
int targetSort = getById(targetId).getSort();
update(getById(sourceId).setSort(targetSort));
update(getById(targetId).setSort(sourceSort));
}
@Override
public int insert(User item) {
try {
item.setSort(maxOfFieldItem("sort").getSort() + 1);
}catch (Exception e){
item.setSort(1);
e.printStackTrace();
}
return super.insert(item);
}
}
Github ORMLiteDemo
DEMO

More Related Content

What's hot

Morphia: Simplifying Persistence for Java and MongoDB
Morphia:  Simplifying Persistence for Java and MongoDBMorphia:  Simplifying Persistence for Java and MongoDB
Morphia: Simplifying Persistence for Java and MongoDBJeff Yemin
 
Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Rebecca Grenier
 
Indexing & Query Optimization
Indexing & Query OptimizationIndexing & Query Optimization
Indexing & Query OptimizationMongoDB
 
MongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaMongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaScott Hernandez
 
Simplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaSimplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaMongoDB
 
MongoDB and Indexes - MUG Denver - 20160329
MongoDB and Indexes - MUG Denver - 20160329MongoDB and Indexes - MUG Denver - 20160329
MongoDB and Indexes - MUG Denver - 20160329Douglas Duncan
 
Indexing and Query Optimization
Indexing and Query OptimizationIndexing and Query Optimization
Indexing and Query OptimizationMongoDB
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickHermann Hueck
 
Java Development with MongoDB
Java Development with MongoDBJava Development with MongoDB
Java Development with MongoDBScott Hernandez
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaMongoDB
 
[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)croquiscom
 
MongoDB Performance Tuning
MongoDB Performance TuningMongoDB Performance Tuning
MongoDB Performance TuningPuneet Behl
 
Getting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETTomas Jansson
 
Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Scott Leberknight
 
Tips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationTips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationJoni
 
Optimizing Slow Queries with Indexes and Creativity
Optimizing Slow Queries with Indexes and CreativityOptimizing Slow Queries with Indexes and Creativity
Optimizing Slow Queries with Indexes and CreativityMongoDB
 
Mythbusting: Understanding How We Measure Performance at MongoDB
Mythbusting: Understanding How We Measure Performance at MongoDBMythbusting: Understanding How We Measure Performance at MongoDB
Mythbusting: Understanding How We Measure Performance at MongoDBMongoDB
 
Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Hermann Hueck
 
Lean React - Patterns for High Performance [ploneconf2017]
Lean React - Patterns for High Performance [ploneconf2017]Lean React - Patterns for High Performance [ploneconf2017]
Lean React - Patterns for High Performance [ploneconf2017]Devon Bernard
 

What's hot (20)

Morphia: Simplifying Persistence for Java and MongoDB
Morphia:  Simplifying Persistence for Java and MongoDBMorphia:  Simplifying Persistence for Java and MongoDB
Morphia: Simplifying Persistence for Java and MongoDB
 
Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access
 
Indexing & Query Optimization
Indexing & Query OptimizationIndexing & Query Optimization
Indexing & Query Optimization
 
MongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaMongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with Morphia
 
Simplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaSimplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with Morphia
 
MongoDB and Indexes - MUG Denver - 20160329
MongoDB and Indexes - MUG Denver - 20160329MongoDB and Indexes - MUG Denver - 20160329
MongoDB and Indexes - MUG Denver - 20160329
 
Indexing and Query Optimization
Indexing and Query OptimizationIndexing and Query Optimization
Indexing and Query Optimization
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with Slick
 
Java Development with MongoDB
Java Development with MongoDBJava Development with MongoDB
Java Development with MongoDB
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and Morphia
 
[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)
 
MongoDB Performance Tuning
MongoDB Performance TuningMongoDB Performance Tuning
MongoDB Performance Tuning
 
Getting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NET
 
Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0
 
Why Sifu
Why SifuWhy Sifu
Why Sifu
 
Tips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationTips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET Application
 
Optimizing Slow Queries with Indexes and Creativity
Optimizing Slow Queries with Indexes and CreativityOptimizing Slow Queries with Indexes and Creativity
Optimizing Slow Queries with Indexes and Creativity
 
Mythbusting: Understanding How We Measure Performance at MongoDB
Mythbusting: Understanding How We Measure Performance at MongoDBMythbusting: Understanding How We Measure Performance at MongoDB
Mythbusting: Understanding How We Measure Performance at MongoDB
 
Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8
 
Lean React - Patterns for High Performance [ploneconf2017]
Lean React - Patterns for High Performance [ploneconf2017]Lean React - Patterns for High Performance [ploneconf2017]
Lean React - Patterns for High Performance [ploneconf2017]
 

Similar to ORMLite Android

Achilles presentation
Achilles presentationAchilles presentation
Achilles presentationDuyhai Doan
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code DevelopmentPeter Gfader
 
Kotlin : Happy Development
Kotlin : Happy DevelopmentKotlin : Happy Development
Kotlin : Happy DevelopmentMd Sazzad Islam
 
Cassandra rapid prototyping with achilles
Cassandra rapid prototyping with achillesCassandra rapid prototyping with achilles
Cassandra rapid prototyping with achillesDuyhai Doan
 
Owasp.meet up.2017.ppt
Owasp.meet up.2017.pptOwasp.meet up.2017.ppt
Owasp.meet up.2017.pptSul Haedir
 
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp KrennPaintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp KrennJavaDayUA
 
Persisting Data on SQLite using Room
Persisting Data on SQLite using RoomPersisting Data on SQLite using Room
Persisting Data on SQLite using RoomNelson Glauber Leal
 
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"epamspb
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme SwiftMovel
 
DConf 2016 std.database (a proposed interface & implementation)
DConf 2016 std.database (a proposed interface & implementation)DConf 2016 std.database (a proposed interface & implementation)
DConf 2016 std.database (a proposed interface & implementation)cruisercoder
 
少し幸せになる技術
少し幸せになる技術少し幸せになる技術
少し幸せになる技術kamedon39
 
Java Generics Adoption: How New Features are Introduced Championed or Ignored
Java Generics Adoption: How New Features are Introduced Championed or IgnoredJava Generics Adoption: How New Features are Introduced Championed or Ignored
Java Generics Adoption: How New Features are Introduced Championed or IgnoredChris Parnin
 
Expression trees in C#
Expression trees in C#Expression trees in C#
Expression trees in C#Oleksii Holub
 
R. herves. clean code (theme)2
R. herves. clean code (theme)2R. herves. clean code (theme)2
R. herves. clean code (theme)2saber tabatabaee
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokusHamletDRC
 
Fast REST APIs Development with MongoDB
Fast REST APIs Development with MongoDBFast REST APIs Development with MongoDB
Fast REST APIs Development with MongoDBMongoDB
 

Similar to ORMLite Android (20)

Achilles presentation
Achilles presentationAchilles presentation
Achilles presentation
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code Development
 
Kotlin : Happy Development
Kotlin : Happy DevelopmentKotlin : Happy Development
Kotlin : Happy Development
 
Cassandra rapid prototyping with achilles
Cassandra rapid prototyping with achillesCassandra rapid prototyping with achilles
Cassandra rapid prototyping with achilles
 
Owasp.meet up.2017.ppt
Owasp.meet up.2017.pptOwasp.meet up.2017.ppt
Owasp.meet up.2017.ppt
 
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp KrennPaintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
 
Persisting Data on SQLite using Room
Persisting Data on SQLite using RoomPersisting Data on SQLite using Room
Persisting Data on SQLite using Room
 
Clean code
Clean codeClean code
Clean code
 
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
 
DConf 2016 std.database (a proposed interface & implementation)
DConf 2016 std.database (a proposed interface & implementation)DConf 2016 std.database (a proposed interface & implementation)
DConf 2016 std.database (a proposed interface & implementation)
 
少し幸せになる技術
少し幸せになる技術少し幸せになる技術
少し幸せになる技術
 
Java Generics Adoption: How New Features are Introduced Championed or Ignored
Java Generics Adoption: How New Features are Introduced Championed or IgnoredJava Generics Adoption: How New Features are Introduced Championed or Ignored
Java Generics Adoption: How New Features are Introduced Championed or Ignored
 
Expression trees in C#
Expression trees in C#Expression trees in C#
Expression trees in C#
 
R. herves. clean code (theme)2
R. herves. clean code (theme)2R. herves. clean code (theme)2
R. herves. clean code (theme)2
 
Basic java for Android Developer
Basic java for Android DeveloperBasic java for Android Developer
Basic java for Android Developer
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
 
Minicurso Android
Minicurso AndroidMinicurso Android
Minicurso Android
 
Fast REST APIs Development with MongoDB
Fast REST APIs Development with MongoDBFast REST APIs Development with MongoDB
Fast REST APIs Development with MongoDB
 
JAVASCRIPT CHEAT SHEET PDF
JAVASCRIPT CHEAT SHEET PDFJAVASCRIPT CHEAT SHEET PDF
JAVASCRIPT CHEAT SHEET PDF
 

More from 哲偉 楊

Specification unit test by Spek
Specification unit test by SpekSpecification unit test by Spek
Specification unit test by Spek哲偉 楊
 
Code kata 的自我修煉
Code kata 的自我修煉Code kata 的自我修煉
Code kata 的自我修煉哲偉 楊
 
輕輕鬆鬆產生 changelog
輕輕鬆鬆產生 changelog輕輕鬆鬆產生 changelog
輕輕鬆鬆產生 changelog哲偉 楊
 
Speed up add custom marker on google map
Speed up add custom marker on google mapSpeed up add custom marker on google map
Speed up add custom marker on google map哲偉 楊
 
Jenkins for android developer at TWJUG
Jenkins for android developer at TWJUGJenkins for android developer at TWJUG
Jenkins for android developer at TWJUG哲偉 楊
 
自己的 Jenkins 自己來 for Android developer
自己的 Jenkins 自己來  for Android developer自己的 Jenkins 自己來  for Android developer
自己的 Jenkins 自己來 for Android developer哲偉 楊
 
從開發到上線的華麗大冒險
從開發到上線的華麗大冒險從開發到上線的華麗大冒險
從開發到上線的華麗大冒險哲偉 楊
 
Kotlin初體驗
Kotlin初體驗Kotlin初體驗
Kotlin初體驗哲偉 楊
 
Kotlin 初體驗
Kotlin 初體驗Kotlin 初體驗
Kotlin 初體驗哲偉 楊
 
Unit test and ui testing with cucumber
Unit test and ui testing with cucumberUnit test and ui testing with cucumber
Unit test and ui testing with cucumber哲偉 楊
 
RxJava With retrolambda
RxJava With retrolambdaRxJava With retrolambda
RxJava With retrolambda哲偉 楊
 
設計師合作經驗分享
設計師合作經驗分享設計師合作經驗分享
設計師合作經驗分享哲偉 楊
 
Hybrid design with bootstrap
Hybrid design with bootstrapHybrid design with bootstrap
Hybrid design with bootstrap哲偉 楊
 

More from 哲偉 楊 (17)

Specification unit test by Spek
Specification unit test by SpekSpecification unit test by Spek
Specification unit test by Spek
 
Code kata 的自我修煉
Code kata 的自我修煉Code kata 的自我修煉
Code kata 的自我修煉
 
Coding dojo
Coding dojoCoding dojo
Coding dojo
 
輕輕鬆鬆產生 changelog
輕輕鬆鬆產生 changelog輕輕鬆鬆產生 changelog
輕輕鬆鬆產生 changelog
 
Speed up add custom marker on google map
Speed up add custom marker on google mapSpeed up add custom marker on google map
Speed up add custom marker on google map
 
Spek
SpekSpek
Spek
 
Jenkins for android developer at TWJUG
Jenkins for android developer at TWJUGJenkins for android developer at TWJUG
Jenkins for android developer at TWJUG
 
自己的 Jenkins 自己來 for Android developer
自己的 Jenkins 自己來  for Android developer自己的 Jenkins 自己來  for Android developer
自己的 Jenkins 自己來 for Android developer
 
從開發到上線的華麗大冒險
從開發到上線的華麗大冒險從開發到上線的華麗大冒險
從開發到上線的華麗大冒險
 
Kotlin初體驗
Kotlin初體驗Kotlin初體驗
Kotlin初體驗
 
Kotlin 初體驗
Kotlin 初體驗Kotlin 初體驗
Kotlin 初體驗
 
Unit test and ui testing with cucumber
Unit test and ui testing with cucumberUnit test and ui testing with cucumber
Unit test and ui testing with cucumber
 
RxJava With retrolambda
RxJava With retrolambdaRxJava With retrolambda
RxJava With retrolambda
 
設計師合作經驗分享
設計師合作經驗分享設計師合作經驗分享
設計師合作經驗分享
 
Dog point
Dog pointDog point
Dog point
 
Gson
GsonGson
Gson
 
Hybrid design with bootstrap
Hybrid design with bootstrapHybrid design with bootstrap
Hybrid design with bootstrap
 

Recently uploaded

Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAbhinavSharma374939
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 

Recently uploaded (20)

9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog Converter
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 

ORMLite Android

  • 2. About me • 哲偉、Andy 、⼩小⽺羊 • Android Code Club • Every Wed. 19:00 - 22:00 果⼦子咖啡 • Android third-party gitbook • Join us • Android Developer
  • 6.
  • 11. Data Table User @DatabaseTable(tableName = "User") public class User { @DatabaseField(generatedId = true) private int id; @DatabaseField private String name; @DatabaseField private int sort; @ForeignCollectionField private ForeignCollection<Group> groups; public User() {} }
  • 12. Data Table Group @DatabaseTable(tableName = "Group") public class Group { @DatabaseField(generatedId = true) private int id; @DatabaseField private String name; @DatabaseField private String description; @DatabaseField(foreign = true, foreignAutoRefresh = true, canBeNull = false, columnName = "user_id") private User user; public Group() {} }
  • 13. public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "Demo"; private static DatabaseHelper instance; private DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public static synchronized DatabaseHelper getHelper(Context context) { context = context.getApplicationContext(); if (instance == null) { synchronized (DatabaseHelper.class) { if (instance == null) instance = new DatabaseHelper(context); } } return instance; } } DatabaseHelper
  • 14. onCreate & onUpdate @Override public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) { try { TableUtils.dropTable(connectionSource, User.class, true); TableUtils.dropTable(connectionSource, Group.class, true); onCreate(database, connectionSource); } catch (SQLException e) { e.printStackTrace(); } } @Override public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) { try { TableUtils.createTable(connectionSource, User.class); TableUtils.createTable(connectionSource, Group.class); } catch (SQLException e) { e.printStackTrace(); } }
  • 15. Abstract Base Dao public abstract class BaseDao<T, ID> { private Dao<T, ID> dao; private DatabaseHelper helper; public BaseDao(Context context, Class<T> clazz) { try { helper = DatabaseHelper.getHelper(context); dao = helper.getDao(clazz); } catch (SQLException e) { e.printStackTrace(); } } public Dao<T, ID> getDao() { return dao; } }
  • 16. CRUD public int insert(T item) { int id; try { id = dao.create(item); } catch (SQLException e) { e.printStackTrace(); id = -1; } return id; } public int deleteById(ID primaryKey) { int id; try { id = dao.deleteById(primaryKey); } catch (SQLException e) { e.printStackTrace(); id = -1; } return id; } public int update(T item) { int id; try { id = dao.update(item); } catch (SQLException e) { e.printStackTrace(); id = -1; } return id; } public T getById(ID id) { try { return dao.queryForId(id); } catch (SQLException e) { e.printStackTrace(); return null; } }
  • 17. getAll, max, minpublic List<T> getAll() { try { return dao.queryBuilder().orderBy("id", false).query(); } catch (SQLException e) { e.printStackTrace(); return Collections.emptyList(); } } public List<T> getAll(boolean isAsc) { try { return dao.queryBuilder().orderBy("id", isAsc).query(); } catch (SQLException e) { e.printStackTrace(); return Collections.emptyList(); } } public List<T> getAll(String field, boolean isAsc) { try { return dao.queryBuilder().orderBy(field, isAsc).query(); } catch (SQLException e) { e.printStackTrace(); return Collections.emptyList(); } } public T maxOfFieldItem(String field) throws Exception { return dao.queryBuilder().orderBy(field, false).limit(1L).query().get(0); } public T minOfFieldItem(String field) throws Exception { return dao.queryBuilder().orderBy(field, true).limit(1L).query().get(0); }
  • 18. Transaction public void insertWithTransaction(final List<T> items) { try { TransactionManager.callInTransaction(helper.getConnectionSource(), new Callable<Void>() { @Override public Void call() throws Exception { for (T t : items) { dao.create(t); } return null; } }); } catch (SQLException e) { e.printStackTrace(); } }
  • 19. Custom Dao public class UserDao extends BaseDao<User, Integer>{ public UserDao(Context context) { super(context, User.class); } public void swap(int sourceId, int targetId) { int sourceSort = getById(sourceId).getSort(); int targetSort = getById(targetId).getSort(); update(getById(sourceId).setSort(targetSort)); update(getById(targetId).setSort(sourceSort)); } @Override public int insert(User item) { try { item.setSort(maxOfFieldItem("sort").getSort() + 1); }catch (Exception e){ item.setSort(1); e.printStackTrace(); } return super.insert(item); } }
  • 21. DEMO