-
-
- Overview
- Leisurely green water beside the forest invasion of the Sunset View Mountain Siwang back
- The Lonely moon in the ancient temple of the forest, cold Kankaka Blue mirror Taiwan
- Gull-fishermen, pan-Crane and leisure pavilion cyclamen
- Walk the path of the flower smoke on the Stream brook far Zhao a canopy open
Overview
A careless has written three, I do not know if you can understand it? If you do not understand the best to leave a message to me, I am good next time to correct.
And then the last time, the preparation is done, and now we're going to start solving the five questions that block Android database operation generalization.
-
Let's review the question first:
-
Issue 1: Getting the table name
-
Issue 2: How to import data from an entity into a database according to the corresponding relationship
-
Question 3: Who is the primary key in an explicit entity? Gets the value encapsulated in the primary key
-
question 4: How to set the data of a table column in a database, by correspondence, encapsulated into an entity in
-
Issue 5: Object creation of an entity
Leisurely green water beside the forest invasion, sunset View Mountain Siwang back.
The problem is, of course, one solution, so it's efficient, so the first question comes: How to get the table name .
Usually, when solving a problem, it starts with a method or function, and this time, we give a shell first:
/** 问题一:表名的获取 **/publicgetTableName() { returnnull;}
Everything is full of hope, and it seems so natural. Now we're going to start thinking about how to get the name of the table.
In actual development, each database table will correspond to a specific entity. It's like news a table corresponds to a News class. Look at them, aren't they similar names? Only one is capitalized and the other is all lowercase. So we think so, if we can get the table name by "entity" .
Since there is a way to see, we know that the way to walk or not go through.
-
We can propose two options:
-
① If we can get to the entity, then we can get the simple name of the entity, and then we just need to put the first letter lowercase is the table name. However, this shortcoming is also obvious, which requires that the name of the database definition table and the name of the entity are basically consistent, which will result in the restriction of the entity names we define. For example
news , if you define a table, the corresponding entity can only be News .
-
② uses annotations so that the relationship between the name of the entity and the name of the database table can be detached from each other. The shortcomings are obvious, the coding difficulty increases, but who call us an experienced developer, choose this kind of.
If there is a classmate comments forgotten, or is not very clear, you can see my article: http://blog.csdn.net/biezhihua/article/details/43783165
The ancient temple of the Lonely Moon, Cold Kankaka blue mirror Taiwan.
Clear the road, all the way forward is possible.
The next step is to use annotations and reflections!! is not a little excited ~ haha ~
The next task is to 给News add an annotation to the entity class, and the purpose of adding annotations is to determine the relationship between the database table and the corresponding entity. Please look at the code:
// 注解的作用:将数据库表和对应的实体确定下来。@TableName(DBHelper.TABLE_NEWS_NAME)publicclass News { privateint id; private String title; private String summary;}
It looks smarty pants, but @TableName(DBHelper.TABLE_NEWS_NAME) what is this sentence? Who can tell me?
This is the note we wrote, but, at this time we have not created it, but it does not matter, if you are using Eclipse, please select this line Ctrl+1 , you can automatically create, so tall, is not shocked! (^ω^). Take a look at the specific TableName code:
/** * 制定了实体和数据库中表的对应关系 */@Target// 指定放置的位置@Retention// 指定存活时间public @interface TableName { /** * 数据库中的表名,此处可以存放值 */ String value();}
Everything is so simple and clear, people feel relaxed and happy. Now that the annotations have been created, the annotations on the entity have been added and the table names have been passed in. Next in the getTableName method, continue to fill in the code is good.
-
Getting a table name is still two steps:
-
① gets the entity to the object-this is the problem five
-
② Gets the annotations on the entity header, and determines the table of operations, based on the value setting.
The first step in the pseudo-code is to get to the object's entity, after viewing, this happens to be the fifth question, we first put, write an empty method to represent.
/** * 问题五:实体对象的创建 */privategetInstance() { returnnull;}
The specific getTableName() method code is as follows:
publicgetTableName() { // 伪代码: // ① 问题五:获取到对象的实体 M m = getInstance(); // ② 获取实体头上的注解,依据value的设置值,确定操作的数据库表 // 需要注意的,想要在“运行时”获取到注解的信息,给注解设置存活时间。 // annotationType 注解的类型 // 为了安全起见,判断注解的合法性;合法则返回value值 ifnull) { return tableName.value(); } returnnull;}
With this method, the BaseDaoSupport delete method can be written out, still very simple, see the code:
@Overridepublicintdelete(Serializable id) { return"=?"new String[] { id.toString() });}
Summary: in fact, in the table name acquisition, we are using annotations to solve a thing, the table and the entity is one by one corresponding to the corresponding relationship between them. (TableName)
Gull Fly full Pu fishermen pan, Crane Companion Leisure Pavilion cyclamen.
It's time to perform the real technology!! (╰_╯) #
It's time to solve the second problem, How to import the data in the entity into the database according to the corresponding relationship.
Recall that the solution to the first problem, in fact, is to use annotations to solve the relationship between the table and the entity. The second issue, in turn, requires that the data in the entity be imported into the database according to the corresponding relationship. The same way of thinking, continue down, you can be a field of the entity annotation, to reflect the database table and the corresponding relationship between the columns. Please look at the code:
/** * 制定了实体的子对岸和数据库表中列的对应关系 */@Target// 指定放置的位置@Retention// 指定存活时间public @interface Column { String value();}
As long as there is this annotation on the field, it must correspond to the columns in the database table, then add the corresponding annotations to the fields of the entity and pass in the column names. Please look at the code:
//the role of annotations: the database tables and corresponding entities are determined. @TableName (dbhelper.table_news_name) Public class news { //specifies the corresponding relationship of the entities and tables in the database @Column (dbhelper.table_id) private int ID; @Column (Dbhelper.table_news_title) private String title; @Column (dbhelper.table_news_summary) private String summary;}
The preparation is ready, the next step is to fill insert in the code, here a new fillColumn(M m, ContentValues values) method, the Entity M field value and the field Column(XXX) annotation in the name of the column, the method is filled into the values.put(key,value) valeus, in order to insert fill in the data. The code is as follows:
@Overridepubliclonginsert(M m) { new ContentValues(); // m代表数据源,vlaues是数据导入的目标 fillColumn(m, values); returnnull, values);}
The code is simple and the key is fillColumn(m, values); to populate the data. By using the reflection technique, get M all the field collections to the instance, get the values of each field and the values of each field annotation, and fill values in the code:
/** * Question two: How to import data from an entity into a database according to the corresponding relationship * * @param m Data source * @param values are the target of data import */ Public void Fillcolumn(M m, contentvalues values) {//Get all the fields on Mfield[] fields = M.getclass (). Getdeclaredfields (); for(Field field:fields) {//Set access rightsField.setaccessible (true);//Get annotations on a field headerColumn column = Field.getannotation (column.class);if(Column! =NULL) {Try{String key = Column.value ();//Gets the name of the specified column in the annotationString value = Field.get (M). ToString ();//Get field values //Fill in the dataValues.put (key, value); }Catch(IllegalArgumentException e) {Throw NewRuntimeException ("field does not belong to M instances"); }Catch(Illegalaccessexception e) {Throw NewRuntimeException ("No Access to field fields"); } } }}
Summary: as long as you have mastered the ideas and methods, neat, clear code, writing is not so difficult.
Travel path tread The smoke on the walk, Stream Brook far Zhao a canopy opens.
Life does not meet, moving like a participating business.
I ask the light candle.
When lions can, the temples are all pale.
Revisiting half for ghosts, exclaimed hot in the intestines.
20, the Gentleman Hall.
Never married, the children suddenly ...
How to generalize the operation of Android database (iii)