V. Parameter Maps and Inline Parameters
[nullue = "numeric"] [null = "- 9999999"] /> parametermap> Bracket [] is an optional attribute. The ID attribute of the parametermap element is unique identifier, which cannot be renamed in the same SQL Map XML file. A ParameterMap can contain any multi-type Property elements. (1) Property The Property property refers to the properties name of the JavaBean parameter object in the mappped statement. This attribute name can be used multiple times, it depends on this statement, how many times this property name will appear. E.g: parametermap> Update author set auth_name =? Where auth_name =? update> But if such a method is used, the calling code should be: Author author = new author (); Author.setname ("author three"); SqlmapClient.Update ("UpdateauThor2", Paramap; Then it actually executed: Update author set auth_name = 'author three' where auth_name = 'author three' In this case, it doesn't make sense, because you can only pass an Author object, and this Author object's Name property value will be used in the entire SQL statement, and in general, it should be the same, That is to say, our originality may be: Update author set auth_name = 'author n' where auth_name = 'author three' The method is that there is, but I don't think it is good. parametermap> Update author set auth_name =? Where auth_name =? update> The call code is: Hashmap paramap = new hashmap (); Paramap.put ("Name1", "author n"); Paramap.put ("name2", "author three"); SqlmapClient.Update ("UpdateauThor2", Paramap; If you think of a better way to solve this problem, please let me know. (2) JDBCTYPE JDBCTYPE is used to specify the field type of the database. If you do not explain the field type, some JDBC drivers cannot determine the type of fields to operate. For example: PreparedStatement.SetNull (int parameterindex, int SQLTYPE) method requires the specified data type. If the data type is not specified, some Driver may be specified as types.other or types.null. However, it cannot guarantee that all Driver is consistent. For this case, the SQL Map API allows the data type to be specified using the JDBCTYPE attribute of the ParameterMap element. Normally, the TYPE property is only required when the field can be NULL or date time type. Because Java has only one Date type (java.util.date), most SQL databases have multiple - usually at least three. Therefore, you need to specify the field type is DATE or DateTime. The Type property can be a string value of any parameter defined in the JDBC Types class. Even so, some types are not supported (ie, BLOB). note! Most JDBC Driver only needs to specify the Type property when the field can be NULL. Therefore, for these Driver, only the Type property needs to be specified when the field can be NULL. note! When using Oracle Driver, if the Type property is not given to the field that can be NULL, "Invalid Column. Type" error occurred when trying to assign a value null. (3) javatype JavaType is used to specify the type of properties of Java beans as parameters. Typically, this can be obtained from the Java Bean by reflecting mechanisms, but some specific mappings, such as MAP and XML mapping cannot pass type information to the framework. This type will be specified as Object if the Java Type is not set and the frame cannot know the type. (4) NULLVALUE The value of the attribute NULLVALUE can be an arbitrary value for the Property type, which is used to specify the replacement value of the NULL. That is, when the attribute value of the Java bean is equal to the specified value, the corresponding field will assign NULL. This feature allows the NULL to assign NULL (ie int, double, float, etc.) to be assigned NULLs in the application. When these data types of property values match the nullue value (ie, match -9999), NULL will replace the Nullue value to write the database. E.g: parametermap> INSERT INTO AUTHOR (auth_name, auth_age, auth_tel, auth_address) VALUES (?,?,?,?) INSERT> You can reference ParameterMap in another SQL Map XML file. For example, to reference the above parametermap in another file, you can use the name "Product.Isert-Product-PARAM". (5) INLINE parameter Maps With Inline Parameter Maps, you can embed the property name of the Java Bean in the definition of mapped-statement (ie, write directly in the SQL statement). E.g: INSERT INTO AUTHOR (auth_name, auth_age, auth_tel, auth_address) values (#Name #, # age #, # Telephone #, # address #) INSERT> This way, in your Author class, there must be Name, AGE, Telephone, Address properties, and corresponding GET and SET methods, which can avoid the use of additional definition parametermap. You can also specify data types and NULLVALUE in the inner parameters, for example: INSERT INTO AUTHOR (auth_name, auth_age, auth_tel, auth_address) Values (#Name: varcha: no_entry #, # age: integer: -999 #, # telephone: varchar: no_entry #, # address: varchar: no_entry #) INSERT> note! In the inner embedded parameters, you must specify an alternate value of NULL, you must first specify the data type. note! If you need to use NULL alternatives, you must be defined in ResultMap at the time of query. note! If you need to specify a lot of data types and null alternative values, you can use external parametermap elements so that the code is clearer. Sixth, Result Maps In the SQL Map architecture, Result Map is an extremely important component. When Query Mapped Statement is executed, ResultMap is responsible for map the column value of the result set to the properties of the Java Bean. The structure of ResultMap is as follows: [ColumnIndex = "1"] [javatype = "int"] [jdbctype = "numeric"] [nullvalue = "- 999999"] [select = "somehaetherstate"] /> resultMap> Bracket [] is an optional property ResultMap also has a Class property, which is a fully qualified name of the Java class (ie, the name of the package) or the alias of the class. This Java class is initialized and populated according to definitions. Extends is an optional properties that can be set to the name of another ResultMap of the basis. And inherited a class in Java, the attribute of the parent ResultMap will serve as part of the sub-resultmap. The attribute of the parent ResultMap is always adding to the front of the subcomeultmap property, and the parent ResultMap must be defined before the sub-resultmap. The Class property of the parent ResultMap and sub-RESultMap is not necessarily consistent, and they can have no relationships. Resultmap can include any multi-type Property mapping, map the column values of the query result set into the properties of the Java Bean. The mapping of the property is performed in the order defined in the ResultMap. The property class must comply with the Java Bean specification, and each property must have a GET / SET method. note! The column value of the ResultSet is read in the order in which they are defined in ResultMap. (1) Property The Property property refers to the properties of the JavaBean object returned from the mapped statement. This attribute name can also be used multiple times. (2) Column The Column property value is the column name in the ResultSet, that is, the field name, the value of this field, will assign the bean property referred to in Property. (3) ColumnIndex Optional properties for improvement of performance. The value of the property ColumnIndex is a field number of fields used to assign a Java bean property in the ResultSet. In 99% of our applications, it is unlikely to sacrifice readability to exchange performance. With ColumnIndex, some JDBC Driver can greatly improve performance, and some do not have any effects. (4) JDBCTYPE JDBCTYPE in ParameterMap (5) javatype Javatype in parametermap (6) NULLVALUE Property NullValue Specifies the alternate value of NULL in the database. Therefore, if the NULL value is read from the ResultSet, the JavaBean property will be assigned the alternative value specified by the attribute NullValue. If there is a field of a nullable property in the database, you want to replace NULL with the specified constant in your application, you can do this: resultMap> In the above example, if the value of the auth_name field in the acquired record is NULL, the Name property will be assigned to "You Have No Name" when assigning Java Beans. (7) SELECT complex attributes If there is a relationship between a class and another class, how does this association implementation when you use JDBC to get a record? For example, such a relationship: A man may have multiple articles to publish, then the author is a strong relationship between the author and the article, and is a couple of relationships, written in the AUTHOR bean: public class author { Private int ID; ..... PRIVATE LIST ARTICLIST; Public int getID () { Return ID; } Public void setid (INT ID) { THIS.ID = ID; } ... Public List GetArticleList () { Return articles; } Public void setArticleList (List Articles) { THIS.Articlelist = Articles.Articlelist; } } When you perform a SQL statement takes the corresponding data from the Data Sheet Author, how do ArticleList assigns? At this time, you need to use the SELECT property. 1.1: 1 Relationship: We first assume that the relationship between Author and Article, although it is incorrect in the real world, we just do an example, then Author and Article's bean code as follows: Public Class Author { Private int ID; PRIVATE INT AGE; PRIVATE STRING NAME; PRIVATE STRING ADDRESS PRIVATE STRING TELEPHONE; PRIVATE ARTICLE; Public int getID () { Return ID; } Public void setid (INT ID) { THIS.ID = ID; } Public int getage () { Return Age; } Public void setage (int Age) { THIS.AGE = AGE; } Public string getName () { Return Name; } Public void setname (String name) { THIS.NAME = Name; } Public String getAddress () { Return Address; } Public void setaddress (String Address) { THIS.ADDRESS = Address; } Public string getTelePhone () { Return televor } Public void settelephone (String Televhone) { This.Telephone = Televhone; } Public article getArticle () { Return this.Article; } Public void setArticle (Article Article) { THIS.Article = Article; } } Public Class Article { Private int ID; PRIVATE STRING TITLE; Private date createtime; PRIVATE INTAUTHOR; Public int getID () { Return ID; } Public void setid (int id) { THIS.ID = ID; } Public string gettitle () { Return Title; } Public void setTitle (String Title) { THIS.TITLE = Title; } Public Date getcreatetime () { Return CreateTime; } Public void setcreatetime (Date CreateTime) { This.createtime = CreateTime; } Public int getAuthor () { Return Author; } Public void setauthor (int Author) { THIS.AUTHOR = Author; } } The configuration in Author.xml is as follows: resultMap> Select * from author where auth_id = # id # select> SELECT ART_ID AS ID, ART_TITLE As Title, Art_CREATETIME AS CREATETIME, ART_AUTHOR AS Author from Article Where Art_ID = # id # select> The calling code is as follows: Author Author = (Author) SQLMAPCLIENT.QUERYFOROBJECT ("GetAuthor5", New Integer (1)); System.out.println (Author.getName () "'s Article IS:" Author.getArticle (). Gettitle ()); You can see that for Article properties in the Author class, iBATIS is incorporated into the statement of the recorded auth_id field value as a parameter into the id = "getLinkArticle1", and encapsulates the result into an Article object, and assigns it to Author's Article property. The two SQL statements actually executed on the above call code are: select * from author where auth_id = 1 SELECT ART_ID AS ID, ART_TITLE As Title, Art_CREATETIME AS CREATETIME, ART_AUTHOR AS Author from Article Where Art_ID = 1 In the second statement, the acquired record is encapsulated into an Article object and assigneed to the ARTICLE property of Author, so you can use Author.getArticle () directly to get the title of the article. The above method shows how to achieve the relationship between 1: 1, but the above method is not good, the reason is that many queries may be executed! (1) Avoid N 1 SELECTS (1: 1) If the above configuration is as follows: resultMap> Select * from author where auth_id> # id # select> SELECT ART_ID AS ID, ART_TITLE As Title, Art_CREATETIME AS CREATETIME, ART_AUTHOR AS Author from Article Where Art_ID = # id # select> The calling code is as follows: Author author = (author) SQLMapClient.QueryforList ("getauThor5", new integer (1)); if the record of select * from author where auth_id> 1 has N, then the ID = "getLinkArticle1" executes N times inquiry Such all the total queries will be N 1 times, and the execution efficiency will be low. At this time, you can use the following combination queries to solve: resultMap> # id # and a.auth_id = B. Art_id]]> select> The call code is: Author author = (author) SQLMAPCLIENT.QUERYFORLIST ("GetAuthor6", New Integer (1)); This can be solved using only one SQL statement. 2.1: M and M: N relationship: Let's discuss the relationship of 1: m, an Author may have multiple Article, so the Author and Article are a pair of relationships. Then we add the following code in the Author class (at the time you want to join): Public Class Author { ... PRIVATE LIST ARTICLIST; Public List GetArticleList () { Return articles; } Public void setArticleList (List Articles) { THIS.Articlelist = Articles.Articlelist; } ... } The configuration is as follows: resultMap> Select * from author where auth_id = # id # select> SELECT ART_ID AS ID, Art_TITLE As Title, Art_Createtime As Createtime, Art_AUTHOR AS Author from Article Where Art_AUTHOR = # id # select> The call code is: Author author = (author) SQLMAPCLIENT.QUERYFOROBJECT ("GetAuthor7", New Integer (1)); System.out.println (Author.getName () "article is:"); For (int i = 0; i { INT NUM = I 1; Article ART = (articles) Author.getArticleList (). Get (i); System.out.println (NUM "." Art.gettitle ()); } As can be seen from the above implementation, you only need to join a java.util.list (or java.util.collection) version of ArticleList to represent all articles list, the call part has no change, IBAITS will automatically The records obtained from Article are encapsulated into an Article object and join a list object, and then assign this List object to the ArticleList property of the Author class. (1) Avoid N 1 SELECTS (1: M and M: N) 1: M and M: N, similar to 1: 1, there is also a case of n 1 Selects, but to the current location, there is no other way to solve this problem, and I hope to solve in the near future. 3. Multiple complex parameter properties You may have noticed that in the example above, only a column property is specified in the ResultMap for the Statement association of id = "getLinkArticle". In fact, iBATIS allows you to specify the Statement association with id = "getLinkArticle", the syntax is simple, {param1 = column1, param2 = column2, ..., paramn = columnn}. Below is an example: resultMap> Select * from author where auth_id = # id # select> SELECT ART_ID AS ID, ART_TITLE As Title, Art_CREATETIME AS CREATETIME, ART_AUTHOR AS Author from Article Where Art_AUTHOR = # id # and art_publish_add = # address # select> You can also write only the name of the field, just follow the words corresponding to the relevant Statement, like this: {auth_id, auth_address} This example I have run in the mysql environment, the reported error is: column '{auth_id, auth_address}' not found. This error is not related to the JDBC driver, but when doing XML analysis, I don't know why. If you have such a successful experience, I hope to share together, my email is: Tenwang1977 @ 163. COM Note: Some JDBC drivers do not support multiple ResultSets at the same time. So, such a driver cannot complete the mapping of complex objects, because JDBC drivers require multiple ResultSets to connect, this time, only one associated query solves the problem. If you use Microsoft SQL Server 2000 JDBC driver, you need to add SelectMethod = Cursor when you configure the URL. 4. Parameters supported in Parameter Maps and Result Maps Java Type JavaBean / MAP Property Mapping Result Class / Parameter Class *** Type Alias ** Boolean Yes no Boolean Java.lang.Boolean Yes Yes Boolean Byte Yes Yes Yes Byte Short Yes No Short Java.lang.short Yes Yes Short Int Yes No int / Integer java.lang.integer Yes Yes Int / Integer Long Yes no long java.lang.long Yes Yes long float Yes no float java.lang.float YES YES FLOAT DOUBLE Yes no double java.lang.double YES YES DOUBLE JAVA.LANG.STRING YES YES STRING JAVA.UTIL.DATE Yes Yes Date Java.math.bigDecimal YES YES DECIMAL * JAVA.SQL.DATE YES YES N / A * JAVA.SQL.Time Yes Yes N / A * Java.sql.TimeStamp Yes Yes N / A Seven, cache mapped statement results cachemodel> The above Cache Model created a cache called "Product-Cache", using the "User Use" (LRU) implementation, every 24 hours, the buffer will be refreshed once, and when executing INSERTPRODUCT, UPDATEPRODUCT, and DELETEPRODUCT STATEMENT, The buffer also refreshes, the set time can be set to Hours, Minutes, Seconds, or MilliseConds. Some Cache implementations require additional properties, such as Cache-size in the above example. Attributes, the size of Cache indicates the number of entities that can be stored in Cache. The name of the TYPE property is either a fully qualified class name or a cache an alias. Cache Model uses a plugin to support different cache algorithms. It implements specified in the TYPE attribute of the cache-model element (as shown above). (1) Read-Only and Read / WRITE IBATIS supports read-only and readable Cache, read-only Cache can share in all users, so it provides greater operating space. However, the object read from the read-only buffer cannot be modified. If you want to modify the object you get, then you can only use readable writable buffers. Readonly = "True" is read-only buffer; readonly = "false" is readable write buffer. (2) Serializable Read / WRITE CACHES To use Serializable Read / Write Caches, set readonly = "false", serialize = "true". By default, readonly = "true", serialize = "false". (3) Cash type Currently, the following four buffer types are currently included: 1. "met," (com.ibatis.db.sqlmap.cache.memory.MemoryCacheController) Memory Cache implements the use of the Reference type to manage Cache's behavior. The garbage collector can determine whether the data in Cache is to be reclaimed according to the Reference type. Memory implementation is applicable to applications that have no unified object reuse modes, or insufficient memory applications. Memory implementation can be configured: cache-model> Memory Cache implementation only knows a (1) Weak (default) In most cases, the WEAK type is the best choice. If you do not specify a type, the default type is Weak. It greatly improves the performance of common queries. However, for the query result data that is currently not used, it will be cleared to release the memory to allocate other objects. (2) Soft In the case where the query result object data is not used, the Soft type will reduce the possibility of insufficient memory in the case of memory allocation of other objects. However, this is not the most intrusive REFERENCE type, and the result data may still be cleared. (3) Strong Make sure the query result data remains in memory unless the Cache is refreshed (for example, the time to refresh or the operation of updating the data is performed). This is an ideal choice for the situation below: 1 "Results The content data is very small 2 "Complete static data 3 "frequent data The advantage is that this kind of query performance is very good. Disadvantages is that if you need to assign other objects, memory cannot be released (it may be more important data objects). 2. "lru" (com.ibatis.db.sqlmap.cache.lru.lrucacheController) Lru Cache implements how to use the "least least use" principle to determine how to clear the object from Cache. When cache overflows, the most recently used object will be cleared from Cache. cache-model> It is worth noting that the object referred to here can be arbitrary, from a single String object to the ArrayList object of Java Bean. Therefore, don't cache too much object to avoid insufficient memory. 3. "FIFO" (com.ibatis.db.sqlmap.cache.fifo.fifocacheController) FIFO Cache implements the "advanced first out" principle to determine how to clear the object from Cache. For the case of continuous reference to a specific query in a short period of time, the FIFO Cache is a good choice. cache-model> It is worth noting that the object referred to here can be arbitrary, from a single String object to the ArrayList object of Java Bean. Therefore, don't cache too much object to avoid insufficient memory. 4. "OSCache" (com.ibatis.db.sqlmap.cache.oscache.oscachecontroller) The OSCache Cache implementation is a plugin for the Oscache 2.0 cache engine. It has a high degree of configurability, distributed, and highly flexible. cache-model> Oscache implementation does not use cache-property elements. Instead, the standard OSCache.Properties file is configured in the root path of the class path. In the oscache.properties file, you can configure Cache's algorithm (similar to the algorithms discussed above), Cache size, persistence method (memory, file, etc.) and cluster methods. For more detailed information, please refer to the OSCache document. Oscache and its documents can get from the OpenSymphony website: http://www.opensymphony.com/oscache/