SlideShare ist ein Scribd-Unternehmen logo
1 von 20
Downloaden Sie, um offline zu lesen
Room with Testing
and Rxjava
報告⼈人:Vincent
• ⽤用過sqlite

• ⽤用過dao

• ⽤用過room
• ⽤用過sqlite

• ⽤用過dao

• ⽤用過room
Gradle
implementation “android.arch.persistence.room:runtime:$room_version”
// use kapt for Kotlin
annotationProcessor “android.arch.persistence.room:compiler:$room_version"
// optional - RxJava support for Room
implementation "android.arch.persistence.room:rxjava2:$room_version"
Room architecture
RoomDatabase
@Database(entities = {WordMain.class, WordInfo.class, WordExample.class,
SearchTime.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract WordMainDao wordMainDao();
public abstract WordInfoDao wordInfoDao();
public abstract WordExampleDao wordExampleDao();
public abstract SearchTimeDao searchTimeDao();
}
class AppDbHepler{
AppDatabase appDatabase = Room.databaseBuilder(context, AppDatabase.class,
dbName).build();
appDatabase.wordMainDao();
appDatabase.wordInfoDao();
appDatabase.wordExampleDao();
appDatabase.searchTimeDao();
}
Entity
@Entity(indices={@Index(value="word", unique=true)})
public class WordMain {
@PrimaryKey
@NonNull
private String wordid;
@NonNull
@ColumnInfo(name = “English_Word")
private String word;
private int times;
}
Wordid English_word Times
1 One 1
Data Access Object (DAO)
@Dao
public interface WordMainDao {
@Insert
void insert(WordMain wordMain);
@Delete
void delete(WordMain wordMain);
@Update
void update(WordMain wordMain);
@Query("SELECT * FROM WordMain WHERE word IN (:word)")
Single<List<WordMain>> loadByword(String word);
}
Insert,Update,Delete
@Insert(onConflict = OnConflictStrategy.IGNORE)
void insert(WordMain wordMain);
@Delete
void delete(WordMain... wordMain);
@Update
void update(List<WordMain> wordMain);
OnConflictStrategy
@Insert //ABORT
void insert(WordMain wordMain);
@Insert(onConflict = OnConflictStrategy.FAIL)
void insert(WordMain wordMain);
@Insert(onConflict = OnConflictStrategy.IGNORE)
void insert(WordMain wordMain);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(WordMain wordMain);
@Insert(onConflict = OnConflictStrategy.ROLLBACK)
void insert(WordMain wordMain);
Query
@Query("SELECT * FROM WordMain WHERE word IN (:word)")
List<WordMain> loadByword(String word);
@Query("SELECT * FROM WordMain w INNER JOIN SearchTime s ON w.wordid
= s.wordid group by w.wordid order by s.searchtime desc")
List<WordMain> loadAll();
@Query("SELECT * FROM WordMain w INNER JOIN SearchTime s ON w.wordid
= s.wordid WHERE s.searchtime BETWEEN :from AND :to group by
w.wordid order by s.searchtime desc")
List<WordMain> findWordMainBetweenDates(Date from, Date to);
RxJava
@Query("SELECT * FROM WordMain WHERE word IN (:word)")
Flowable<List<WordMain>> loadByword(String word);
@Query("SELECT * FROM WordMain w INNER JOIN SearchTime s ON w.wordid
= s.wordid group by w.wordid order by s.searchtime desc")
Maybe<List<WordMain>> loadAll();
@Query("SELECT * FROM WordMain w INNER JOIN SearchTime s ON w.wordid
= s.wordid WHERE s.searchtime BETWEEN :from AND :to group by
w.wordid order by s.searchtime desc")
Single<List<WordMain>> findWordMainBetweenDates(Date from, Date to);
TypeConverter
public class DateConverters {
@TypeConverter
public static Date fromTimestamp(Long value) {
return value == null ? null : new Date(value);
}
@TypeConverter
public static Long dateToTimestamp(Date date) {
return date == null ? null : date.getTime();
}
}
@Database(entities = {WordMain.class}, version = 1)
@TypeConverters({DateConverters.class})
public abstract class AppDatabase extends RoomDatabase {
……
}
Relation
單字 中英⽂文解釋 例例句句
Relation
@Entity(foreignKeys = @ForeignKey(entity = WordInfo.class,
parentColumns = "wordinfoid",
childColumns = "wordinfoid"),
indices={@Index(value="wordinfoid")})
public class WordExample {
…..
}
public class WordTotalInfo {
@Embedded
WordInfo wordInfo;
@Relation(parentColumn = "wordinfoid",
entityColumn = "wordinfoid", entity = WordExample.class)
List<WordExample> wordExamples;
…..
}
@Dao
public interface WordInfoDao {
@Query("SELECT * FROM WordInfo WHERE wordid IN (:wordid)")
Single<List<WordTotalInfo>> loadAllByIds(String wordid);
….
}
Testing
Testing
public class WordInfoDaoTest {
AppDatabase db;
@Before
public void setUp() throws Exception {
db = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext()
,AppDatabase.class).build();
}
@After
public void tearDown() throws Exception {
db.close();
}
}
@Test
public void OnConflictStrategy_ROLLBACK() {
try {
db.wordMainDao().insert(new WordMain("PrimaryKey3", "test", 123));
db.beginTransaction();
db.runInTransaction(new Runnable() {
@Override
public void run() {
List<WordMain> wordMains = new ArrayList<>();
wordMains.add(new WordMain("PrimaryKey2", "test1", 124));
wordMains.add(new WordMain("PrimaryKey3", "test7", 125));
db.wordMainDao().insert(wordMains);
db.setTransactionSuccessful();
}
});
} catch (Exception e) {
System.out.print(e.toString());
}
db.wordMainDao().all().subscribe(new SingleObserver<List<WordMain>>() {
@Override
public void onSubscribe(Disposable d) {}
@Override
public void onSuccess(List<WordMain> wordMains) {
Assert.assertThat(wordMains.size(), is(1));
Assert.assertThat(wordMains.get(0).getWordid(), is("PrimaryKey3"));
Assert.assertThat(wordMains.get(0).getWord(), is("test"));
Assert.assertThat(wordMains.get(0).getTimes(), is(123));
}
@Override
public void onError(Throwable e) {
System.out.print(e.toString());
}
});
}
@Test
public void wordTotalInfoQuery() {
wordMain = new WordMain("wordid3", "test", 123);
wordInfo = new WordInfo("wordinfoid2", "wordid3", "4", "5", "6");
wordExample = new WordExample("7", "wordinfoid2", "9", "10");
db.wordMainDao().insert(wordMain);
db.wordInfoDao().insert(wordInfo);
db.wordExampleDao().insert(wordExample);
Single<List<WordTotalInfo>> s = db.wordInfoDao().loadAllByIds("3");
s.subscribe(new Consumer<List<WordTotalInfo>>() {
@Override
public void accept(List<WordTotalInfo> wordTotalInfos) throws
Exception {
WordTotalInfo wordTotalInfo = wordTotalInfos.get(0);
WordInfo wordInfo = wordTotalInfo.getWordInfo();
WordExample wordExample = wordTotalInfo.getWordExamples().get(0);
Assert.assertThat(wordInfo.getWordinfoid(), is("wordinfoid2"));
Assert.assertThat(wordInfo.getWordid(), is("wordid3"));
Assert.assertThat(wordInfo.getChinesemean(), is("4"));
Assert.assertThat(wordInfo.getEnglishmean(), is("5"));
Assert.assertThat(wordInfo.getType(), is("6"));
Assert.assertThat(wordExample.getExampleid(), is("7"));
Assert.assertThat(wordExample.getWordinfoid(), is("wordinfoid2"));
Assert.assertThat(wordExample.getExample(), is("9"));
Assert.assertThat(wordExample.getExampletranslate(), is("10"));
}
});
}
Q&A

Weitere ähnliche Inhalte

Was ist angesagt?

Optimizing Tcl Bytecode
Optimizing Tcl BytecodeOptimizing Tcl Bytecode
Optimizing Tcl Bytecode
Donal Fellows
 
TclOO: Past Present Future
TclOO: Past Present FutureTclOO: Past Present Future
TclOO: Past Present Future
Donal Fellows
 
SH 1 - SES 7 - Change-Streams-Tel-Aviv.pptx
SH 1 - SES 7 - Change-Streams-Tel-Aviv.pptxSH 1 - SES 7 - Change-Streams-Tel-Aviv.pptx
SH 1 - SES 7 - Change-Streams-Tel-Aviv.pptx
MongoDB
 

Was ist angesagt? (20)

Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24  tricky stuff in java grammar and javacJug trojmiasto 2014.04.24  tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
 
Optimizing Tcl Bytecode
Optimizing Tcl BytecodeOptimizing Tcl Bytecode
Optimizing Tcl Bytecode
 
TclOO: Past Present Future
TclOO: Past Present FutureTclOO: Past Present Future
TclOO: Past Present Future
 
Making an Object System with Tcl 8.5
Making an Object System with Tcl 8.5Making an Object System with Tcl 8.5
Making an Object System with Tcl 8.5
 
Refactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech TalkRefactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech Talk
 
Cs267 hadoop programming
Cs267 hadoop programmingCs267 hadoop programming
Cs267 hadoop programming
 
Effective testing for spark programs scala bay preview (pre-strata ny 2015)
Effective testing for spark programs scala bay preview (pre-strata ny 2015)Effective testing for spark programs scala bay preview (pre-strata ny 2015)
Effective testing for spark programs scala bay preview (pre-strata ny 2015)
 
Beyond parallelize and collect - Spark Summit East 2016
Beyond parallelize and collect - Spark Summit East 2016Beyond parallelize and collect - Spark Summit East 2016
Beyond parallelize and collect - Spark Summit East 2016
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
Andrzej Ludwikowski - Event Sourcing - co może pójść nie tak?
Andrzej Ludwikowski -  Event Sourcing - co może pójść nie tak?Andrzej Ludwikowski -  Event Sourcing - co może pójść nie tak?
Andrzej Ludwikowski - Event Sourcing - co może pójść nie tak?
 
Mongo db
Mongo dbMongo db
Mongo db
 
RxJava from the trenches
RxJava from the trenchesRxJava from the trenches
RxJava from the trenches
 
SH 1 - SES 7 - Change-Streams-Tel-Aviv.pptx
SH 1 - SES 7 - Change-Streams-Tel-Aviv.pptxSH 1 - SES 7 - Change-Streams-Tel-Aviv.pptx
SH 1 - SES 7 - Change-Streams-Tel-Aviv.pptx
 
Scalding - Hadoop Word Count in LESS than 70 lines of code
Scalding - Hadoop Word Count in LESS than 70 lines of codeScalding - Hadoop Word Count in LESS than 70 lines of code
Scalding - Hadoop Word Count in LESS than 70 lines of code
 
Clojure: a LISP for the JVM
Clojure: a LISP for the JVMClojure: a LISP for the JVM
Clojure: a LISP for the JVM
 
Scalding for Hadoop
Scalding for HadoopScalding for Hadoop
Scalding for Hadoop
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 features
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
 

Ähnlich wie Room with testing and rxjava

Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
Alexey Buzdin
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
C.T.Co
 

Ähnlich wie Room with testing and rxjava (20)

Annotation processing and code gen
Annotation processing and code genAnnotation processing and code gen
Annotation processing and code gen
 
Finding the right stuff, an intro to Elasticsearch (at Rug::B)
Finding the right stuff, an intro to Elasticsearch (at Rug::B) Finding the right stuff, an intro to Elasticsearch (at Rug::B)
Finding the right stuff, an intro to Elasticsearch (at Rug::B)
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Data Types/Structures in DivConq
Data Types/Structures in DivConqData Types/Structures in DivConq
Data Types/Structures in DivConq
 
Mobile Day - React Native
Mobile Day - React NativeMobile Day - React Native
Mobile Day - React Native
 
NET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptxNET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptx
 
Применение паттерна Page Object для автоматизации веб сервисов - новый взгляд
Применение паттерна Page Object для автоматизации веб сервисов - новый взглядПрименение паттерна Page Object для автоматизации веб сервисов - новый взгляд
Применение паттерна Page Object для автоматизации веб сервисов - новый взгляд
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
NLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by OrdinaNLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by Ordina
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web Stack
 
Android dev toolbox
Android dev toolboxAndroid dev toolbox
Android dev toolbox
 
Querydsl fin jug - june 2012
Querydsl   fin jug - june 2012Querydsl   fin jug - june 2012
Querydsl fin jug - june 2012
 
Building a GraphQL API in PHP
Building a GraphQL API in PHPBuilding a GraphQL API in PHP
Building a GraphQL API in PHP
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
 
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition! Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
 
React native
React nativeReact native
React native
 
Android Sample Project By Wael Almadhoun
Android Sample Project By Wael AlmadhounAndroid Sample Project By Wael Almadhoun
Android Sample Project By Wael Almadhoun
 
Android Jetpack: Room persistence library
Android Jetpack: Room persistence libraryAndroid Jetpack: Room persistence library
Android Jetpack: Room persistence library
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 

Kürzlich hochgeladen

notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
MsecMca
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
dollysharma2066
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 

Kürzlich hochgeladen (20)

Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 

Room with testing and rxjava

  • 1. Room with Testing and Rxjava 報告⼈人:Vincent
  • 4. Gradle implementation “android.arch.persistence.room:runtime:$room_version” // use kapt for Kotlin annotationProcessor “android.arch.persistence.room:compiler:$room_version" // optional - RxJava support for Room implementation "android.arch.persistence.room:rxjava2:$room_version"
  • 6. RoomDatabase @Database(entities = {WordMain.class, WordInfo.class, WordExample.class, SearchTime.class}, version = 1) public abstract class AppDatabase extends RoomDatabase { public abstract WordMainDao wordMainDao(); public abstract WordInfoDao wordInfoDao(); public abstract WordExampleDao wordExampleDao(); public abstract SearchTimeDao searchTimeDao(); } class AppDbHepler{ AppDatabase appDatabase = Room.databaseBuilder(context, AppDatabase.class, dbName).build(); appDatabase.wordMainDao(); appDatabase.wordInfoDao(); appDatabase.wordExampleDao(); appDatabase.searchTimeDao(); }
  • 7. Entity @Entity(indices={@Index(value="word", unique=true)}) public class WordMain { @PrimaryKey @NonNull private String wordid; @NonNull @ColumnInfo(name = “English_Word") private String word; private int times; } Wordid English_word Times 1 One 1
  • 8. Data Access Object (DAO) @Dao public interface WordMainDao { @Insert void insert(WordMain wordMain); @Delete void delete(WordMain wordMain); @Update void update(WordMain wordMain); @Query("SELECT * FROM WordMain WHERE word IN (:word)") Single<List<WordMain>> loadByword(String word); }
  • 9. Insert,Update,Delete @Insert(onConflict = OnConflictStrategy.IGNORE) void insert(WordMain wordMain); @Delete void delete(WordMain... wordMain); @Update void update(List<WordMain> wordMain);
  • 10. OnConflictStrategy @Insert //ABORT void insert(WordMain wordMain); @Insert(onConflict = OnConflictStrategy.FAIL) void insert(WordMain wordMain); @Insert(onConflict = OnConflictStrategy.IGNORE) void insert(WordMain wordMain); @Insert(onConflict = OnConflictStrategy.REPLACE) void insert(WordMain wordMain); @Insert(onConflict = OnConflictStrategy.ROLLBACK) void insert(WordMain wordMain);
  • 11. Query @Query("SELECT * FROM WordMain WHERE word IN (:word)") List<WordMain> loadByword(String word); @Query("SELECT * FROM WordMain w INNER JOIN SearchTime s ON w.wordid = s.wordid group by w.wordid order by s.searchtime desc") List<WordMain> loadAll(); @Query("SELECT * FROM WordMain w INNER JOIN SearchTime s ON w.wordid = s.wordid WHERE s.searchtime BETWEEN :from AND :to group by w.wordid order by s.searchtime desc") List<WordMain> findWordMainBetweenDates(Date from, Date to);
  • 12. RxJava @Query("SELECT * FROM WordMain WHERE word IN (:word)") Flowable<List<WordMain>> loadByword(String word); @Query("SELECT * FROM WordMain w INNER JOIN SearchTime s ON w.wordid = s.wordid group by w.wordid order by s.searchtime desc") Maybe<List<WordMain>> loadAll(); @Query("SELECT * FROM WordMain w INNER JOIN SearchTime s ON w.wordid = s.wordid WHERE s.searchtime BETWEEN :from AND :to group by w.wordid order by s.searchtime desc") Single<List<WordMain>> findWordMainBetweenDates(Date from, Date to);
  • 13. TypeConverter public class DateConverters { @TypeConverter public static Date fromTimestamp(Long value) { return value == null ? null : new Date(value); } @TypeConverter public static Long dateToTimestamp(Date date) { return date == null ? null : date.getTime(); } } @Database(entities = {WordMain.class}, version = 1) @TypeConverters({DateConverters.class}) public abstract class AppDatabase extends RoomDatabase { …… }
  • 15. Relation @Entity(foreignKeys = @ForeignKey(entity = WordInfo.class, parentColumns = "wordinfoid", childColumns = "wordinfoid"), indices={@Index(value="wordinfoid")}) public class WordExample { ….. } public class WordTotalInfo { @Embedded WordInfo wordInfo; @Relation(parentColumn = "wordinfoid", entityColumn = "wordinfoid", entity = WordExample.class) List<WordExample> wordExamples; ….. } @Dao public interface WordInfoDao { @Query("SELECT * FROM WordInfo WHERE wordid IN (:wordid)") Single<List<WordTotalInfo>> loadAllByIds(String wordid); …. }
  • 17. Testing public class WordInfoDaoTest { AppDatabase db; @Before public void setUp() throws Exception { db = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext() ,AppDatabase.class).build(); } @After public void tearDown() throws Exception { db.close(); } }
  • 18. @Test public void OnConflictStrategy_ROLLBACK() { try { db.wordMainDao().insert(new WordMain("PrimaryKey3", "test", 123)); db.beginTransaction(); db.runInTransaction(new Runnable() { @Override public void run() { List<WordMain> wordMains = new ArrayList<>(); wordMains.add(new WordMain("PrimaryKey2", "test1", 124)); wordMains.add(new WordMain("PrimaryKey3", "test7", 125)); db.wordMainDao().insert(wordMains); db.setTransactionSuccessful(); } }); } catch (Exception e) { System.out.print(e.toString()); } db.wordMainDao().all().subscribe(new SingleObserver<List<WordMain>>() { @Override public void onSubscribe(Disposable d) {} @Override public void onSuccess(List<WordMain> wordMains) { Assert.assertThat(wordMains.size(), is(1)); Assert.assertThat(wordMains.get(0).getWordid(), is("PrimaryKey3")); Assert.assertThat(wordMains.get(0).getWord(), is("test")); Assert.assertThat(wordMains.get(0).getTimes(), is(123)); } @Override public void onError(Throwable e) { System.out.print(e.toString()); } }); }
  • 19. @Test public void wordTotalInfoQuery() { wordMain = new WordMain("wordid3", "test", 123); wordInfo = new WordInfo("wordinfoid2", "wordid3", "4", "5", "6"); wordExample = new WordExample("7", "wordinfoid2", "9", "10"); db.wordMainDao().insert(wordMain); db.wordInfoDao().insert(wordInfo); db.wordExampleDao().insert(wordExample); Single<List<WordTotalInfo>> s = db.wordInfoDao().loadAllByIds("3"); s.subscribe(new Consumer<List<WordTotalInfo>>() { @Override public void accept(List<WordTotalInfo> wordTotalInfos) throws Exception { WordTotalInfo wordTotalInfo = wordTotalInfos.get(0); WordInfo wordInfo = wordTotalInfo.getWordInfo(); WordExample wordExample = wordTotalInfo.getWordExamples().get(0); Assert.assertThat(wordInfo.getWordinfoid(), is("wordinfoid2")); Assert.assertThat(wordInfo.getWordid(), is("wordid3")); Assert.assertThat(wordInfo.getChinesemean(), is("4")); Assert.assertThat(wordInfo.getEnglishmean(), is("5")); Assert.assertThat(wordInfo.getType(), is("6")); Assert.assertThat(wordExample.getExampleid(), is("7")); Assert.assertThat(wordExample.getWordinfoid(), is("wordinfoid2")); Assert.assertThat(wordExample.getExample(), is("9")); Assert.assertThat(wordExample.getExampletranslate(), is("10")); } }); }
  • 20. Q&A