- Create abstract class
- Introduce AutoValue
- Maven
- Gradle
- Article catalog
- Delete¶
- Execute delete process ¶
- Search¶
- Add searching process ¶
- Execute searching process ¶
- First, root form
- How to use AutoValue
- 2, annotation class generated Java source code in the app module
- 1, annotate processor code
- Import template project¶
- 3, the Java source code generated in the Library2 module
- Second, generate root tables
- Update¶
- Execute update process ¶
- Test AutoValue
- Insert¶
- Execute insert process ¶
- Fourth, blog resources
- Summary¶
- Install JDK¶
- SQL file¶
- Structure of template project¶
- Setting of Annotation Processor¶
- Third, complete annotation processor code and generated Java code (for reference only)
Create abstract class
comgoogleautovalueAutoValue
Animal String name numberOfLegs
name numberOfLegs
String
AutoValue It is an open source library of Google that can be used to simplify some tedious and repetitive tasks in Java development, such asgetter/setter
、toString()
with equals()
And other methods.
Introduce AutoValue
Maven
<dependency>
<groupId>com.google.auto.value</groupId>
<artifactId>auto-value-annotations</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>com.google.auto.value</groupId>
<artifactId>auto-value</artifactId>
<version>1.6.2</version>
<scope>provided</scope>
</dependency>
Gradle
dependencies {
compile "com.google.auto.value:auto-value-annotations:1.6.2"
annotationProcessor "com.google.auto.value:auto-value:1.6.2"
}
- Set upPreferences -> Build, Execution, Deployment -> Compiler -> Annotation Processors
Set according to the figure below: Allow annotation processor
- Run menu barBuild -> Build Project
- Find allgenerated Directory, right-click menu selectionMark Directory as -> Generated Sources Root
By Nish Tahir
—
So I recently got my hands on Kotlin and it’s been great so far.
The idea plugin isn’t able to mark the kapt folder as a source directory unless it’s been added to the gradle source set.
sourceSets.main.java.srcDir file("$buildDir/generated/source/kapt/")
idea {
module {
// Tell idea to mark the folder as generated sources
generatedSourceDirs += file("$buildDir/generated/source/kapt/")
}
}
When put together your build script should look a little like this.
apply plugin: 'idea'
...
kapt {
generateStubs = true
}
// Add kapt directory to sources
sourceSets.main.java.srcDir file("$buildDir/generated/source/kapt/")
idea {
module {
// Tell idea to mark the folder as generated sources
generatedSourceDirs += file("$buildDir/generated/source/kapt/")
}
}
Footnotes and references
Article catalog
Componentized series blog:
- [Android components] from modular to component
- [Android Component] Use the gradle to implement componentization (Gradle variable definition and use)
- [Android component] Implement componentization using a gradle (component mode and integrated mode switch)
- [Android Component] Use the Gradle to implement componentization (library module development in component / integration mode)
- [Android component] routing components (routing component structure)
- [Android component] routing components (annotation processor gets annotated nodes)
- [Android components] Routing components (annotation processors use JavaPOET generation code)
- [Android components] Routing components (annotation processor parameter option settings)
- [Android component] routing component (constructed routing information in the routing table)
- [Android component] Routing components (using JavaPoEt build routing tables)
- [Android Component] Routing Components (Serviced Services between Components)
Delete¶
Execute delete process¶
You confirm that next code is exists at .
Execute delete process by using this code.
You add next code to .
// First transaction // Execute deleting // Second transaction // Confirm that deleting is success
You execute JUnit and confirm that this code is run.
At that time, created for the deleting SQL is next.
Identifier and version number is specified in search condition.
Search¶
Add searching process¶
Show how to adding process that searching young employee than arbitrary age.
You add next program code to and execute build.
At this time, next error message is shown on Message tool window by annotation process.
You create file that name is selectByAge.sql to under and rebuild by keeping empty file.
Error message content will change.
You back to file and describe next SQL.
/* age */
You rebuild then error is resolved.
Execute searching process¶
Actually execute the created searching process at the above.
You add next code to .
You execute JUnit and confirm that this code is run.
At that time, created for the searching SQL is next.
First, root form
kimhslrouter
javalangOverride
javalangString
javautilMap
kimhsllibrary2StringService
kimhslroute_coretemplateIRouteGroup
kimhslrouter_annotationmodelRouteBean
Map atlas
atlas RouteBeanTypeISERVICE StringService
The module name is App, then the name of the routing table is router_group_app.java;
There may be multiple routing tables in a module, and you need to regenerate a root table for a number of routing tables for navigation of routing tables;
Generated root table style: where «app» is a group name, Router_Group_app.class is a routing table class corresponding to the APP group;
kimhslrouter
javalangClass
javalangOverride
javalangString
javautilMap
kimhslroute_coretemplateIRouteGroup
kimhslroute_coretemplateIRouteRoot
MapString Class routes
routes Router_Group_app
How to use AutoValue
The concept of AutoValue is very simple: you write an abstract entity class and hand it over to AutoValue to implement it.
2, annotation class generated Java source code in the app module
In the Module module, use the source code generated by the annotation, all in the «build \ generation \ ap_generated_sources \ debug \ out \» directory of the corresponding module;
Note in the app:
path
Bundle savedInstanceState
savedInstanceState
Rlayoutactivity_main
The generated routing source code: Generating source path D: \ 002_project \ 002_Android_learn \ Component \ App \ Build \ generated \ AP_GENERATED_SORES \ Debug \ OUT \ KIM \ HSL \ ROUTER \ ROUTER_GROUP_APP.JAVA;
kimhslrouter
javalangOverride
javalangString
javautilMap
kimhslcomponentMainActivity
kimhslroute_coretemplateIRouteGroup
kimhslrouter_annotationmodelRouteBean
Map atlas
atlas RouteBeanTypeACTIVITY MainActivity
The generated root table source code: Generating source path D: \ 002_project \ 002_Android_learn \ Component \ App \ Build \ generated \ ap_generated_sources \ debug \ out \ kim \ HSL \ ROUTER \ ROUTER_ROOT_APP.JAVA;
kimhslrouter
javalangClass
javalangOverride
javalangString
javautilMap
kimhslroute_coretemplateIRouteGroup
kimhslroute_coretemplateIRouteRoot
MapString Class routes
routes Router_Group_app
1, annotate processor code
kimhslrouter_compiler
comgoogleautoserviceAutoService
comsquareupjavapoetClassName
comsquareupjavapoetJavaFile
comsquareupjavapoetMethodSpec
comsquareupjavapoetParameterSpec
comsquareupjavapoetParameterizedTypeName
comsquareupjavapoetTypeSpec
comsquareupjavapoetWildcardTypeName
javaioIOException
javautilArrayList
javautilHashMap
javautilMap
javautilSet
javautilTreeMap
javaxannotationprocessingAbstractProcessor
javaxannotationprocessingFiler
javaxannotationprocessingMessager
javaxannotationprocessingProcessingEnvironment
javaxannotationprocessingProcessor
javaxannotationprocessingRoundEnvironment
javaxannotationprocessingSupportedAnnotationTypes
javaxannotationprocessingSupportedOptions
javaxannotationprocessingSupportedSourceVersion
javaxlangmodelSourceVersion
javaxlangmodelelementElement
javaxlangmodelelementModifier
javaxlangmodelelementTypeElement
javaxlangmodeltypeTypeMirror
javaxlangmodelutilElements
javaxlangmodelutilTypes
javaxtoolsDiagnostic
kimhslrouter_annotationRoute
kimhslrouter_annotationmodelRouteBean
javaxlangmodelelementModifierPUBLIC
/ / Note the parameters received by the processor
// Automatically register annotation processor
Processor
// Supported annotations
// Supported Java version
SourceVersionRELEASE_8
/**
* Note to print the log in the processor
*/
Messager mMessager
/**
* Used to write Java code
*/
Filer mFiler
/**
* Note Node Tool
*/
Elements mElementUtils
/**
* Tools
*/
Types mTypeUtils
/**
* Get the moduleName parameters
*/
String mModuleName
/**
* Management routing information
* Key: Routing Group Name
* Value: Routing Information Collection
*/
HashMapString ArrayList mGroupMap
/**
* Manage routing table information
* Key: Group name
* Value: Classification
*/
Map mRootMap
ProcessingEnvironment processingEnvironment
processingEnvironment
/ / Get the print log interface
mMessager processingEnvironment
// Test Log Print
mMessagerDiagnosticKindNOTE "Messager Print Log"
mFiler processingEnvironment
mElementUtils processingEnvironment
mTypeUtils processingEnvironment
/ / Get the moduleName parameters
// Get annotations for the annotation processor
Map options processingEnvironment
options null
mModuleName options
mMessagerDiagnosticKindNOTE "Print MODULENAME parameters:" mModuleName
Set set RoundEnvironment roundEnvironment
set null set
// If there is no annotation, exit directly
// These annotations nodes are class nodes, typelelement types
Set routeElements roundEnvironmentRoute
routeElements
/ / Generate the Java routing table class corresponding to the routing component group table
/ / Generate root routing table, group name <-> routing table class
/**
* Generate root table
*/
// Get kim.hsl.route_core.template.iroutegroup class node
TypeElement iRouteGroup mElementUtils
/ / Get kim.hsl.route_core.template.iRouteroot class node
TypeElement iRouteRoot mElementUtils
/ / Generate parameter type name
// Map<String,Class<? extends IRouteGroup>> routes>
ParameterizedTypeName routesTypeName ParameterizedTypeName
ClassNameMap
ClassNameString
ParameterizedTypeName
ClassNameClass
WildcardTypeNameClassNameiRouteGroup
// Generate parameters
// Map<String,Class<? extends IRouteGroup>> routes> routes
ParameterSpec rootParameterSpec ParameterSpecroutesTypeName
/ / Generate functions
// public void loadInfo(Map<String,Class<? extends IRouteGroup>> routes> routes)
MethodSpecBuilder loadIntoMethodBuilder MethodSpec
Override
ModifierPUBLIC
rootParameterSpec
/ / Generate a function
MapEntry entry mRootMap
loadIntoMethodBuilder
entry
ClassName entry
/ / Generate the root class
String rootClassName mModuleName
// Create a Java class
TypeSpec typeSpec TypeSpecrootClassName
ClassNameiRouteRoot
PUBLIC
loadIntoMethodBuilder
/ / Generate a Java source file
JavaFile javaFile JavaFile typeSpec
// Write into the file
javaFilemFiler
e
e
/**
* Generate the Java class corresponding to the routing component group table
*/
/ / Get interface nodes that need to be implemented
TypeElement iRouteGroup mElementUtils
// Print the class node
mMessagerDiagnosticKindNOTE
"Print the route table needs to be implemented interface nodes IROUTEGROUP:" iRouteGroup
/ / Generate parameter type MAP <String, Routebean> Atlas
ParameterizedTypeName atlasType ParameterizedTypeName
ClassNameMap
ClassNameString
ClassNameRouteBean
// Generate parameters map <string, routebean> Atlas
ParameterSpec atlasValue ParameterSpecatlasType
// Traversing Hashmap <string, arraylist <routebean >> mgroupmap = new hashmap <> () routing group
/ / Create a class for each routing group
MapEntryString ArrayList entry mGroupMap
// Create a function loadinto
MethodSpecBuilder methodBuilder MethodSpec
ModifierPUBLIC
Override
atlasValue
// Code generation in the function body
// Get arraylist <routebean> data
ArrayList groupRoutes entry
// group name
String groupName
/ / Generate a function code
RouteBean routeBean groupRoutes
// Get a group name
groupName routeBean
// $ s represents a string
// $ T represent class
// $ L indicates a word size, and the original stamped string is replaced.
methodBuilder"atlas.put($S, new $T($T.$L, $T.class, $S, $S))"
// $ s string: "main"
routeBean
// $ T Name: Routebean
ClassNameRouteBean
// $ T Name: Type
ClassNameRouteBeanType
// $ L Findex: Activity
routeBean
// $ T Name: kim.hsl.component.mainActivity class
ClassNameTypeElement routeBean
// $ S String: "/ App / MainActivity"
routeBean
// $ s string: "app"
routeBean
// Create a class
/ / Configuration Class name Router_Group_main
String groupClassName groupName
// Create a class
TypeSpec typeSpec TypeSpecgroupClassName
ClassNameiRouteGroup
PUBLIC
methodBuilder
/ / Generate a Java source code file
JavaFile javaFile JavaFile typeSpec
// Write the Java source file to the corresponding directory
mMessagerDiagnosticKindNOTE
groupClassName
javaFilemFiler
e
e
mMessagerDiagnosticKindNOTE
"Output file is abnormal"
mMessagerDiagnosticKindNOTE
"Output file is complete"
// Statistics route table information
mRootMapgroupName groupClassName
Set routeElements
/ / Get the annotation node for Android.App.Activity type
TypeElement activityElement mElementUtils
TypeElement iServiceElement mElementUtils
Element element routeElements
/ / Get ROUTE annotations
Route route elementRoute
// Single routing object in the routing table
RouteBean routeBean null
/ / Judgment whether the Typemirror annotation node is an activity type
mTypeUtilselement activityElement
/ / This node is the Android.App.Activity type
routeBean
RouteBeanTypeACTIVITY // Route object type
element // Route node
null // class object
route // Route address
route // Route group
mTypeUtilselement iServiceElement
// This node is a kim.hsl.route_core.template.Ist type
routeBean
RouteBeanTypeISERVICE // Route object type
element // Route node
null // class object
route // Route address
route // Route group
// This node is not Android.App.Activity type
/ / Check the route address
routeBean
// Print Routing Information
mMessagerDiagnosticKindNOTE
"Print Routing Information:" routeBean
// Processing routing information packet
routeBean
RouteBean routeBean
// First get all routing information from the group from the GroupMap collection
ArrayList routeBeans mGroupMaprouteBean
routeBeans null
// If the route information collection of the packet obtained from mGroupMap is empty
// Create a new collection, put routing information, and join mgroupmap
routeBeans
routeBeansrouteBean
mGroupMaprouteBean routeBeans
/ / The routing information set from the routing group obtained from mgroupmap is not empty
// Directly add routing information
routeBeansrouteBean
RouteBean routeBean
/ / Get the route address
String routeAddress routeBean
// Get routing group
String routeGroup routeBean
// Verify whether the routing address begins with "/"
routeAddress
routeAddress " wrong format"
// If the packet of the route address is empty,
// Intercepted the string between 0 and 1st "/" as a packet name
routeGroup null routeGroup
String group routeAddress
routeAddress
routeAddress
group null group
routeAddress "Get Packet Error"
// Print group name
mMessagerDiagnosticKindNOTE
"Print Routing Address" routeAddress "The group name" group
/ / Officially set routing address grouping
routeBeangroup
Import template project¶
You clone simple-boilerplate from GitHub.
$ git clone https://github.com/domaframework/simple-boilerplate.git
You start IntelliJ IDEA and execute Import Project, select the cloned simple-boilerplate.
You check Import project from external model and select Gradle.
You check Use auto-import and uncheck Create separate module per source set.
Finally you push Finish.
If the message that is synced successfully is shown at Build tool window then import is success.
3, the Java source code generated in the Library2 module
In the Module module, use the source code generated by the annotation, all in the «build \ generation \ ap_generated_sources \ debug \ out \» directory of the corresponding module;
Note from library2:
kimhsllibrary2
androidutilLog
kimhslbaseComponentService
kimhslrouter_annotationRoute
path
Log "StringService service in library2 components"
The generated routing source code: Generating source path D: \ 002_Project \ 002_Android_learn \ Component \ library2 \ build \ generated \ ap_generated_sources \ debug \ out \ kim \ HSL \ ROUTER \ ROUTER_GROUP_LIBRARY2.JAVA;
kimhslrouter
javalangOverride
javalangString
javautilMap
kimhsllibrary2StringService
kimhslroute_coretemplateIRouteGroup
kimhslrouter_annotationmodelRouteBean
Map atlas
atlas RouteBeanTypeISERVICE StringService
The generated root table source code:Generating source path D: \ 002_project \ 002_Android_learn \ company \ library2 \ build \ generated \ ap_generated_sources \ debug \ out \ kim \ HSL \ ROUTER \ ROUTER_ROOT_LIBRARY2.JAVA;
kimhslrouter
javalangClass
javalangOverride
javalangString
javautilMap
kimhslroute_coretemplateIRouteGroup
kimhslroute_coretemplateIRouteRoot
MapString Class routes
routes Router_Group_library2
Second, generate root tables
Define the IrouterOot interface, all the root classes implement this interface, which is defined in the route-core module;
kimhslroute_coretemplate
javautilMap
MapString Class routes
Iroot Interface Defined Location:
First, get the node of the Iroutegroup and IrouterOot interface;
// Get kim.hsl.route_core.template.iroutegroup class node
TypeElement iRouteGroup mElementUtils
/ / Get kim.hsl.route_core.template.iRouteroot class node
TypeElement iRouteRoot mElementUtils
Second, the parameters of the Loadinto function are generated mapp <string, class <? Extensity Iroutegroup >> Routes;
/ / Generate parameter type name
// Map<String,Class<? extends IRouteGroup>> routes>
ParameterizedTypeName routesTypeName ParameterizedTypeName
ClassNameMap
ClassNameString
ParameterizedTypeName
ClassNameClass
WildcardTypeNameClassNameiRouteGroup
// Generate parameters
// Map<String,Class<? extends IRouteGroup>> routes> routes
ParameterSpec rootParameterSpec ParameterSpecroutesTypeName
Again, generate functions and function bodies;
/ / Generate functions
// public void loadInfo(Map<String,Class<? extends IRouteGroup>> routes> routes)
MethodSpecBuilder loadIntoMethodBuilder MethodSpec
Override
ModifierPUBLIC
rootParameterSpec
/ / Generate a function
MapEntry entry mRootMap
loadIntoMethodBuilder
entry
ClassName entry
Finally, generate the router_root_app class and write it into the file;
/ / Generate the root class
String rootClassName mModuleName
// Create a Java class
TypeSpec typeSpec TypeSpecrootClassName
ClassNameiRouteRoot
PUBLIC
loadIntoMethodBuilder
/ / Generate a Java source file
JavaFile javaFile JavaFile typeSpec
// Write into the file
javaFilemFiler
e
e
Update¶
Execute update process¶
You confirm that next code is exists at .
Execute update process by using this code.
You add next code to .
// First transaction // Search and update age field // Second transaction // Confirm that updating is success
You execute JUnit and confirm that this code is run.
At that time, created for the updating SQL is next.
The version number that is for optimistic concurrency control is automatically increment.
Test AutoValue
At this momentCannot resolve symbol 'AutoValue_Animal'
The error message has disappeared, test the Animal class:
Animal dog Animal
dog
dog
Animal dog
Animal dog
Animal dog
dog
Insert¶
Execute insert process¶
You confirm that next code is exists at .
Execute insert process by using this code.
You add next code to .
// First transaction // Execute inserting // Second transaction // Confirm that inserting is success
You execute JUnit and confirm that this code is run.
At that time, created for the inserting SQL is next.
Identifier and version number is automatically setting.
Fourth, blog resources
- GitHub : https://github.com/han1202012/Component
- CSDN Download:
Summary¶
Introduce how to setting up development environment and how to executing basic database access.
Install JDK¶
You install JDK 8 .
Doma support JDK 9 and JDK 10, 11.
SQL file¶
You open file.
This file is described like next.
/* id */
The show that expansioning column list by referencing entity class that is mapped at Java method.
The
show that Java method parameter value is binding to this SQL.
The that is placed at behind is test data.
By including this test data, you can confirm easily that there is not mistake in SQL at executing by tool.
Test data is not used at executing Java program.
About detail you reference .
Structure of template project¶
The project source code’s structure is like next.
─ src ├── main │ ├── java │ │ └── boilerplate │ │ ├── AppConfig.java │ │ ├── dao │ │ │ ├── AppDao.java │ │ │ └── EmployeeDao.java │ │ └── entity │ │ └── Employee.java │ └── resources │ └── META-INF │ └── boilerplate │ └── dao │ ├── AppDao │ │ ├── create.script │ │ └── drop.script │ └── EmployeeDao │ ├── selectAll.sql │ └── selectById.sql └── test ├── java │ └── boilerplate │ ├── DbResource.java │ └── dao │ └── EmployeeDaoTest.java └── resources
Explain about important file.
- AppConfig.java
- The that is needed for executing Doma.
- AppDao.java
- Utility that create/drop the database schema that is using in this application.
This is not need in production environment.
The script file is underand is used for creating and dropping schema.
- Employee.java
- The that correspond to EMPLOYEE table within database.
- EmployeeDao.java
- The that is execute getting and updating
class.
The SQL file is underand is used.
- EmployeeDaoTest.java
- The test that is using
.
You can learn about Doma by adding test case to this file.
Other test is not affected by updating data because database schema is created and disposed per test method.
Setting of Annotation Processor¶
You select Open Module Settings from context menu on tool window.
You open setting screen of Paths of Modules and confirm that Inherit project compile output path is selected.
If it is not selected, you select it.
You open Build, Execution, Deployment > Compiler > Annotation Processors from Preferences.
You check Enable annotation processing.
You check Module content root.
You input gen/production to Production sources directory and input gen/test to Test sources directory.
Finally push OK.