Summary of usage knowledge of MyBatis persistence layer Framework _java

Source: Internet
Author: User
Tags db2 extend generator null null postgresql sybase unique id oracle database

MyBatis is an excellent persistence layer framework that supports common SQL queries, stored procedures, and advanced mappings. MyBatis eliminates the manual setting of almost all JDBC code and parameters and the retrieval of result sets. MyBatis uses simple XML or annotations for configuration and raw mapping, mapping interfaces and Java POJOs (Plain old Java Objects, normal Java objects) to records in the database.

MyBatis is an open source project for Apache Ibatis, the project was migrated from Apache Software Foundation to Google code in 2010 and renamed MyBatis.

November 2013 migration to Github,mybatis GitHub address: https://github.com/mybatis/mybatis-3.

The word ibatis is derived from the combination of "Internet" and "Abatis", a Java-based persistence layer framework. The persistence layer framework provided by Ibatis includes SQL maps and Data Access Objects (DAO).

Each MyBatis application uses the Sqlsessionfactory instance primarily, and a sqlsessionfactory instance can be obtained by Sqlsessionfactorybuilder. Sqlsessionfactorybuilder can be obtained from an XML configuration file or an instance of a predefined configuration class.

1. Use generator to automatically generate DAO layer, model layer and mapper layer.

MyBatis Generator Download Address: http://www.mybatis.org/generator/

MyBatis Generator Chinese Introduction: http://generator.sturgeon.mopaas.com/

The following uses the Mybatis-generator-core-1.3.2.jar plug-in plus the JDBC database connection pack to automatically export the persistence layer DAO package, model package and mapper package.

The Java packages you need to use are:

Mybatis-generator-core-1.3.2.jar,

Mysql-connector-java-5.1.34.jar,

Ojdbc14-10.2.0.1.0.jar,

Sqljdbc4-4.0.jar.

Configuration file: Generator.xml

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE generatorconfiguration Public "-//mybatis.org//dtd mybatis generator Configuration" "1.0//en Mybatis.org/dtd/mybatis-generator-config_1_0.dtd "> <generatorConfiguration> <!--configuration Properties files are used to introduce variables in a configuration file El expression--> <!--if it is run by cmd here should write URL way write full path because classpath is not found for resource--> <!--<properties url= "file:// /d:/workspaces/mybatisgen/bin/generatorconfig.properties "/>--> <!--database driver package location--> <!--SQL Server data driver package --> <classpathentry location= "D:\JavaProject\generator\sqljdbc4-4.0.jar"/> <!--Oracle Data driver package-->
 --<classpathentry location= "D:\Java\m2\repository\com\oracle\ojdbc14\10.2.0.1.0\ojdbc14-10.2.0.1.0.jar"/> --> <!--mysql Data driver package--> <!--<classpathentry location= "D:\JavaProject\generator\ Mysql-connector-java-5.1.34.jar "/>--> <!--Specify the dao--> <!--ID to generate for MYBATIS3: must be configured. The unique identifier for this context.
  The value will be used in some error messages. Defaultmodeltype: Used to define a build model type policy. 1.conditional default policy, generate a model class 2.flat for each table: Create a model class for all tables, that is, this class will save all the fields in the table 3.hierarchical: If the table has a primary key, The model generates a primary key class, another class that holds any BLOB columns in the table, and another class that holds the rest of the fields.
 This is the relationship between an appropriate inheritance class.
  Targetruntime: This property is used to specify the code generated by the Run-time target.
  1.MYBATIS3 defaults generate objects that are compatible MyBatis versions 3.0 and later, and JSE 5.0 and later (for example, the Java model and Mapper interfaces will use generic types).
  The By example method supports an almost infinite dynamic where clause in these generated objects.
  In addition, Java objects and these builder builds support many of the JSE 5.0 features including parameterized types and annotations. 2.ibatis2java2 3.ibatis2java5--> <context id= "mysqltables" targetruntime= "MyBatis3" 
  Conditional "> <!--<plugin type=" Org.mybatis.generator.plugins.EqualsHashCodePlugin "/>--> <!-- Used to generate comment 1. Suppressallcomments The default is False this property is used to specify whether any comments will be included in the generated code. If set to True, no comment 2 is generated.
 Suppressdate default is False This property is used to specify whether the generated comment will include the MBG generation timestamp.
 --> <commentGenerator> <property name= "suppressallcomments" value= "true"/> </commentGenerator> <!--database link URL, username, password--> <!--mysql database link URL, username, password--> <!--<jdbcconnection Driverclass= "Com.mysql.jdbc.Driver" connectionurl= "jdbc:mysql://127.0.0.1:3310/test" userid= "test" password= "1234" > </jdbcConnection>--> <!--Oracle database link URL, username, password--> <!--<jdbcconnection driverclass= "Oracle.jd
 Bc.driver.OracleDriver "connectionurl=" JDBC:ORACLE:THIN:@127.0.0.1:1521:ORCL "userid=" test "password=" 1234 "> </jdbcConnection>--> <!--SQL server database link URL, user name, password--> <jdbcconnection driverclass= "Com.microsoft . Sqlserver.jdbc.SQLServerDriver "Connectionurl=" jdbc:sqlserver://127.0.0.1:1433;databasename=test "userid=" test " password= "1234" > </jdbcConnection> <!--H2 <entry key= "Jdbc.url" >jdbc:h2:tcp://localhost/test< /entry> <entry key= "Jdbc.driver" >org.h2.Driver</entry>--> <!--SQLServer2000 <entry key= "J Dbc.url ">jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=[database]</entry> <entry key=" Jdbc.driver ">COM.MICROSOFT.JDBC.SQLSERVER.SQLSERVERDRIVER</entry>--> <!--SQLServer2005 <entry key= "Jdbc.url" >jdbc:sqlserver://192.168.0.98:1433;d atabasename=[database]</entry> <entry key= "Jdbc.driver" >com.microsoft.sqlserver.jdbc.sqlserverdriver </entry>--> <!--jtds for SQL Server <entry key= "Jdbc.url" >jdbc:jtds:sqlserver://192.168.0.102:1433 /[database];tds=8.0;lastupdatecount=true</entry> <entry key= "Jdbc.driver" > Net.sourceforge.jtds.jdbc.driver</entry>--> <!--PostgreSql <entry key= "Jdbc.url" >JDBC: postgresql://localhost/[database]</entry> <entry key= "Jdbc.driver" >org.postgresql.driver</entry >--> <!--Sybase <entry key= "Jdbc.url" >jdbc:sybase:Tds:localhost:5007/[database]</entry> <e Ntry key= "Jdbc.driver" >com.sybase.jdbc.SybDriver</entry>--> <!--DB2 <entry key= "Jdbc.url" >jdb c:db2://localhost:5000/[database]</entry> <entry key= "Jdbc.driver" >com.ibm.db2.jdbc.apP.db2driver</entry>--> <!--HsqlDB <entry key= "Jdbc.url" >jdbc:hsqldb:mem:generatordb</entry&
  Gt <entry key= "Jdbc.driver" >org.hsqldb.jdbcDriver</entry>--> <!--Derby <entry key= "Jdbc.url" > jdbc:derby://localhost/databasename</entry> <entry key= "Jdbc.driver" > Org.apache.derby.jdbc.clientdriver</entry>--> <!--java type Parser optional configuration--> <!--<javatyperesolver Type= "" > Type property: This can be used to specify a user-supplied Java type parser.
  This class must implement Interface Org.mybatis.generator.api. Javatyperesolver, you must have a public default constructor.
  Properties can also accept special values by default in this case, the default implementation is used (the same effect does not specify the type).
  Properties supported by this label: Forcebigdecimals: Default is false whether to force the use of BigDecimal to represent all decimal and numeric fields.
  • If the size is large and the length is greater than 18, the BigDecimal type is used.
  • If the length is 10 to 18, the Java type Parser replaces the Java.lang.Long.
  • If the length is 5 to 9, then the Java type Parser is replaced with a Java.lang.integer. 
 • If its length is less than 5, the Java type Parser is replaced with Java.lang.Short. --> <javaTypeResolver> <property name= "Forcebigdecimals" value= "false"/> </javaTypeResolver> &L t;! --Generate Vo object--> ≪!
  --the < Javamodelgenerator > element is used to define the properties generated by the Java model. The Java Model Builder establishes primary key classes, records classes, and introspection of tables that match the query sample class.
  This element is the required child element < context > element. Supported properties: constructorbased: This property is used to select whether the MyBatis generator will generate a constructor for a class that accepts each field in a value class.
  Also, the SQL results map will be built into each field using constructors instead of "setter".
  This attribute is only applicable to MYBATIS3 and will be ignored by iBATIS2.
  The default value is False. Immutable: Immutable, this property is used to select whether the MyBatis generator will produce immutable model classes-which means that classes will not have a "setter" method and constructors will accept the values of each field in the class.
  The default is False.
  Trimstrings: This property is used to select whether the MyBatis generator adds code to trim the blank space returned from the database by the character field. This is useful if your database stores data in character fields instead of varchar fields.
  The MyBatis generator inserts code to cut character fields.
 The default value is False. --> <!--generate the package name and location of the entity class, where the generated entity classes are configured to be placed under Com.ouc.model--> <javamodelgenerator targetpackage= " Com.ouc.model "targetproject=" D:\JavaProject\generator\src > <property name= "enablesubpackages" value= "true"
 /> <property name= "trimstrings" value= "true"/> </javaModelGenerator> <!--generate the mapping object for the query--> <!--the generated SQL Map package name and location where the generated SQL map file is placed under the Com.ouc.mapping package--> <sqlmapgenerator targetpackage= " Com.ouc.mapping "targetproject=" D:\JavaPrOject\generator\src "> <property name=" enablesubpackages "value=" true "/> </sqlMapGenerator> <!--generation
  DAO's class files and configuration files--> <!--< Javaclientgenerator > elements are attributes used to define Java client code generators.
  Java client generators are used to establish Java interfaces and classes so that you can easily use the generated Java model and XML mapping files.
  For iBATIS2 target environments, these generated objects take the form of DAO interfaces and implementation classes.
  For MyBatis, the generated object takes the form of an mapper interface.
  This element is an optional child element.
  If you do not specify this element, the MyBatis generator (MBG) does not generate Java client interfaces and classes. Where the Type property is: If Targetruntime is MyBatis3 Xmlmapper: The generated object MyBatis the Java interface to the 3.x mapper infrastructure. The interface will depend on the generated XML mapper file.
 This xmlmapper is commonly used. --> <!--generates the package name and location of the DAO, where it is configured to place the generated DAO class under Com.ouc.dao--> <javaclientgenerator type= "Xmlmapper" Targetpackage= "Com.ouc.dao" targetproject= "D:\JavaProject\generator\src" > <property name= "enablesubpackages" "Value=" true "/> </javaClientGenerator> <!--<table> element is used to select a table in the database.
  The selected table will cause the following objects to be generated for each table: • A mybatis/ibatis formatted SQL mapping file • A set of classes that form a "model" table that includes: • A class to match • The table's primary key (if the table has a primary key). • The fields in the table match, not the primary key, not the BLOB field.
  This class will extend the primary key if there is one. • A class to hold a BLOB field in any table (if any)。
  This class will extend the first two classes of one of them depending on the configuration of the table.
  • A class that is used to generate a dynamic where clause, in a different "by Example" method (Selectbyexample,deletebyexample). • (optional) DAO interface and Class TableName: The name of the specified table must be configured Domainobjectname: The base name of the JavaBean object is generated.
  If not specified, MBG is automatically generated based on the table name.
  The name (either specified here or automatically generated) will be used as the domain class name and the DAO class name. Enableinsert: Whether to generate the INSERT statement. The default is true Enableselectbyprimarykey: whether a selection statement is generated by a primary key.
  Whether or not you have this setting, if the table does not have a primary key, it will not be generated. Enableupdatebyprimarykey: Whether to generate an UPDATE statement through a primary key.
  If the table does not have a primary key, the statement will not be generated, regardless of whether the property is set. Enabledeletebyprimarykey: Whether to generate DELETE statements through primary keys.
  If the table does not have a primary key, the statement will not be generated, regardless of the setting of this property. Enabledeletebyexample: Whether to generate DELETE statements through the example object.
  This declaration causes many different dynamic deletes to be generated at run time. Enablecountbyexample: Whether to generate calculated line count statements through the example object.
  The statement returns the number of rows in a table that matches the example. Enableupdatebyexample: Whether to generate an UPDATE statement through the example object.
  The statement updates the matching records in a table. Selectbyprimarykeyqueryid: This value will be added to the select list via the primary key declaration in this form: "' < value > as Queryid." This can be used to identify queries at the DBA to track tools at run time.
  If you need to use, you should specify a unique ID for each of the different queries generated MBG. Selectbyexamplequeryid: This value will be added to the select list by selecting an example declaration in this table: "' < value > as Queryid." This can be used to identify queries at the DBA to track tools at run time.
  If you need to use, you should specify a unique ID for each of the different queries generated MBG. Enableselectbyexample: Whether a selection statement through example should be generated. This statement makes many different dynamic queries in the shippingRow is generated. Modeltype: This property is used to override the default model type if you want to do so with this table.
  If unspecified, the domain object that MBG will generate is based on the context default model type.
  The model type defines how the MBG domain class will be generated.
  Some model type MBG will generate a single domain class for each table, and other classes that may produce different MBG depending on the structure of the table. Escapewildcards: Exclude wildcard characters.
  This means that regardless of the SQL wildcard character (' _ ' and '% ') patterns and table names should be avoided in the search column.
 This is some driver requirements if the pattern or table contains a SQL wildcard character (for example, if a table's name is my_table, some driver-required underscore characters are escaped). --> <!--to generate those tables (change tablename and domainobjectname can)--> <table tablename= "V_supplyuser" Vsupplyuser "enablecountbyexample=" false "enableupdatebyexample= false" enabledeletebyexample= "false" Enableselectbyexample= "false" selectbyexamplequeryid= "false"/> <table tablename= "Wj_gatelist" Domainobjectname= "Wjgatelist" enablecountbyexample= "false" enableupdatebyexample= false "enabledeletebyexample=" False "enableselectbyexample=" false "selectbyexamplequeryid=" false "/> </context> </ Generatorconfiguration>

Open the cmd command line, go to the file where the configuration file is located, and execute the following build statement:

 
 

Command completed, you can see the corresponding path to generate DAO package, model package and mapper package file.

2.MyBatis Framework Integration

1) mybatis using parameter configuration: Sqlmapconfig.xml.

① cache Configuration (Cache): cacheenabled: Global switch: Default is True, if it is set to false, the remaining mapper XML files to support cache is useless.

② Delay Loading:

Lazyloadingenabled:true uses deferred loading, false disables deferred loading, the default is true, and when disabled, all associated objects are loaded instantly.

When Aggressivelazyloading:true is enabled, all lazy object properties of the object are fully loaded when a lazy object property is accessed in the object when deferred loading is turned on. False, loading object properties on demand (that is, accessing a lazy object property in an object without loading the other lazy object properties in the object) when loading is deferred. The default is true.

③multipleresultsetsenabled: Allows and does not allow a single statement to return multiple datasets (depending on the driver requirements). The default is true.

④usecolumnlabel: Use column labels instead of column names. Different drives have different practices. Refer to the drive documentation, or test with these two different options.

⑤usegeneratedkeys: Allows JDBC to generate primary keys. Drive support is required. If set to true, this setting enforces the generated primary key, and some drives are incompatible but can still be executed.

⑥automappingbehavior: Specifies whether MyBatis and how to automatically map the properties of the data table fields and objects. Partial will only automatically map simple, no nested results. Full will automatically map all the complex results.

⑦defaultexecutortype: Configures and sets the actuator, the simple executor executes other statements. The reuse executor may use the prepared statements statement repeatedly, and the batch executor can repeat the statements and batch updates.

⑧defaultstatementtimeout: Set a time limit to determine how long the drive waits for a database response to timeout.

The full sqlmapconfig.xml configuration file is as follows:

<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE configuration Public "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration> <settings> <setting name= "cacheenabled" value= "true"/> <setting " Lazyloadingenabled "value=" true "/> <setting name=" multipleresultsetsenabled "value=" true "/> Name= ' Usecolumnlabel ' value= ' true '/> <setting name= ' Usegeneratedkeys ' value= ' false '/> <setting ' name= ' Automappingbehavior "value=" PARTIAL "/> <setting name=" Defaultexecutortype "value=" simple "/><!--simple Reuse BATCH--> <!--<setting name= "Defaultexecutortype" value= "BATCH" "/>-->" <setting name= " Defaultstatementtimeout "value=" "/> <setting name=" saferowboundsenabled "value=" false "/> <setting" name= " Mapunderscoretocamelcase "value=" false "/> <setting name=" Localcachescope "value=" session "/> <!--< Setting name= "Jdbctypefornull" vaLue= "Other"/>--> <setting name= "Jdbctypefornull" value= "NULL"/> <setting "name=" Lazyloadtriggermethods "value=" equals,clone,hashcode,tostring "/> </settings> <typeAliases> <!-- Module--> <typealias alias= "User" type= "Com.ouc.mkhl.platform.authority.model.User"/> <typealias "alias=" Role "type=" Com.ouc.mkhl.platform.authority.model.Role "/> <typealias alias=" equipment "type=" Com.ouc.mkhl.platform.basedata.model.Equipment "/> <typealias alias=" Factory "type=" Com.ouc.mkhl.platform.basedata.model.Factory "/> </typeAliases> <typeHandlers> <typehandler handler= "Com.ouc.openplatform.dao.mybatis.SerializableTypeHandler"/> </typeHandlers> </configuration >

Serialization of special value processing: Serializabletypehandler

Package com.ouc.openplatform.dao.mybatis;
Import java.io.Serializable;
Import java.sql.CallableStatement;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import Org.apache.ibatis.type.BaseTypeHandler;
Import Org.apache.ibatis.type.JdbcType; /** * @author wuping */public class Serializabletypehandler extends basetypehandler<serializable> {@Override publi c void Setnonnullparameter (PreparedStatement ps, int i, Serializable parameter, Jdbctype jdbctype) throws SQLException {p
S.setobject (i, parameter); @Override public Serializable Getnullableresult (ResultSet rs, String columnName) throws SQLException {return (Serializa
ble) rs.getobject (columnName); @Override public Serializable Getnullableresult (ResultSet rs, int columnindex) throws SQLException {return (serializabl
e) Rs.getobject (columnindex); @Override public Serializable Getnullableresult (CallableStatement cs, int. columnindex) throws SQLException {return (Ser ializable) Cs.getobJect (columnindex); }
}

2) result set Resultmap:

In MyBatis, the return type can be resulttype for a select mapping in a query, or the return type can be directly represented by Resultmap,resulttype, whereas Resultmap is a reference to an external resultmap. But Resulttype and Resultmap cannot exist at the same time. In MyBatis query mapping, in fact, every query out of the attributes are placed in a corresponding map inside, where the key is the property name, the value is its corresponding value. When the provided return type attribute is Resulttype, MyBatis assigns the key value in the map to the property of the object specified by Resulttype. So in fact, the return type of each query map in MyBatis is Resultmap, but when the return type attribute we provide is Resulttype, mybatis the property that automatically assigns the corresponding value to the object specified by Resulttype. And when we provide the return type is Resultmap, because the map does not represent the domain model well, we need to translate it further into the corresponding object, which is often useful in complex queries.

Example: Userbaseresultmap

<resultmap id= "Userbaseresultmap" type= "User" >
<id column= "id" property= "id" jdbctype= "INTEGER"/>
<result column= "UserName" property= "UserName" jdbctype= "VARCHAR"/> <result "column="
property= "Password" jdbctype= "VARCHAR"/> <result column= "
Email" property= "email" jdbctype= "VARCHAR"/>
<result column= "Truename" property= "Truename" jdbctype= "VARCHAR"/> <result "column=" Sex
"Sex" jdbctype= "VARCHAR"/> <result column= "Age
" property= "Age" jdbctype= "INTEGER"/>
<result column= "Telephone" property= "Telephone" jdbctype= "VARCHAR"/>
</resultMap>

Model class: User

Package Com.ouc.mkhl.platform.authority.model;
Import java.io.Serializable;
 User information public class user implements Serializable {private static final long serialversionuid = 1098321123L; Private Integer ID; User ID private String userName; User name private String password; Unencrypted password private String email; Mailbox Private String Truename; Real name private String sex; Sex private Integer age; Age private String telephone;
 Mobile phone public Integer getId () {return id;
 The public void SetId (Integer id) {this.id = ID;
 Public String GetUserName () {return userName;
 } public void Setusername (String userName) {this.username = UserName = = null? Null:userName.trim ();
 Public String GetPassword () {return password;
 } public void SetPassword (String password) {this.password = password = = null? Null:password.trim ();
 Public String Getemail () {return email;
 } public void Setemail (String email) {this.email = email = null Null:email.trim (); } public String GettruenamE () {return truename;
 } public void Settruename (String truename) {this.truename = Truename = = null? Null:trueName.trim ();
 Public String Getsex () {return sex;
 } public void Setsex (String sex) {this.sex = sex = = null? Null:sex.trim ();
 Public Integer Getage () {return age;
 public void Setage (Integer age) {this.age = age;
 Public String Gettelephone () {return telephone;
 } public void Settelephone (String telephone) {This.telephone = telephone = = null? Null:telephone.trim (); }
}

3) Increase the check:

(1) Select query:

①id: A unique identifier in this mode that can be referenced by other statements.

②parametertype: The full class name or alias of the parameter passed to this statement.

③resulttype: Statement returns an integer class name or alias for a value type. Note that if it is a collection, then the whole class name or alias of the item of the collection is filled in, not the class name of the collection itself. (Resulttype and Resultmap cannot be used)

④resultmap: The external resultmap name referenced. Result set mapping is the most powerful feature in MyBatis. Many complex mappings can be easily solved. (Resulttype and Resultmap cannot be used)

⑤flushcache: If set to true, the cache is emptied each time the statement is invoked. The SELECT statement is set to False by default.

⑥usecache: If set to true, the result set of the statement will be cached. The SELECT statement is set to False by default.

⑦timeout: Sets the maximum time that a drive waits for a response before throwing an exception, and defaults to a value that is determined by the drive itself.

Example: Querying all user information: Selectusers

<select id= "Selectusers" resultmap= "Userbaseresultmap" >
select id,username,email from user 

(2) Insert insertion: Saveuser

The database table here uses the primary key to increment, and the primary key is an ID.

①fetchsize: After setting a value, the drive returns when the number of result sets reaches this value, and the default is no value, determined by the drive itself.

②statementtype:statement,preparedstatement,callablestatement. Prepared statements, callable statements.

③usegeneratedkeys: Use the JDBC Getgeneratedkeys method to get the primary key generated by the database itself (relational databases such as MySQL, SQL Server have automatically generated fields).

④keyproperty: Identifies a value that is returned by a key that will be mybatis into Getgeneratedkeys, or uses a selectkey child element for the INSERT statement.

<insert id= "Saveuser" parametertype= "user" >
insert INTO User (userName, password, emails, truename, sex, age, TE Lephone)
values (#{username,jdbctype=varchar}, #{password,jdbctype=varchar}, 
#{email,jdbctype=varchar}, # {Truename,jdbctype=varchar}, 
#{sex,jdbctype=varchar}, #{age,jdbctype=integer}, #{telephone,jdbctype=varchar} )

(3) Update updates: Dynamic update Sql:updateuser

<update id= "UpdateUser" parametertype= "user" >
update User
<set >
<if test= "UserName!= Null ">
userName = #{username,jdbctype=varchar},
</if>
<if test=" password!= null ">
Password = #{password,jdbctype=varchar},
</if>
<if test= "email!= null" >
email = #{email, Jdbctype=varchar},
</if>
<if test= "truename!= null" >
truename = #{truename,jdbctype= VARCHAR},
</if>
<if test= "sex!= null" >
sex = #{sex,jdbctype=varchar},
</if>
<if test= ' age!= null ' > Age
= #{age,jdbctype=integer},
</if>
<if test= ' telephone != NULL ">
telephone = #{telephone,jdbctype=varchar},
</if>
</set>
where id = #{id , Jdbctype=integer}
</update>

(4) Delete deletion: DeleteUser

<delete id= "DeleteUser" parametertype= "Integer" >
delete from user
where id = #{id,jdbctype=integer}

(5) The Sql:sql element is used to define a reusable SQL statement segment that can be invoked by other statements.

<sql id= "Userbasecolumnlist" >
userName, password, email, telephone
</sql>
<select id= " Getusers "resultmap=" Userbaseresultmap ">
select 
<include refid=" Userbasecolumnlist "/>
from User

(6) Parameter: Parameters:mybatis can use basic data types and Java complex data types.

Basic data types, string,int,date and so on.

With a basic data type, you can provide only one parameter, so you need to use a Java entity class, or a map type, to do the parameter type. The properties can be obtained directly by #{}.

① basic Data type parameters: String

<select id= "Getuserbyname" resulttype= "user" parametertype= "String" >
select ID, userName, email from User
where userName = #{username,jdbctype=varchar}
</select>

Java code:

Public User getuserbyname (String name); Get user information based on user name

②java entity type parameter: User

<insert id= "Saveuser" parametertype= "user" >
insert INTO User (userName, password, emails, truename, sex, age, TE Lephone)
values (#{username,jdbctype=varchar}, #{password,jdbctype=varchar}, 
#{email,jdbctype=varchar}, # {Truename,jdbctype=varchar}, 
#{sex,jdbctype=varchar}, #{age,jdbctype=integer}, #{telephone,jdbctype=varchar} )
</insert>

Java code:

public int saveuser (user user); Insert User Information

③map parameters: map<string, object> Recordmap

<select id= "Selectchildgrouptotalnum" resulttype= "Integer" >
Select COUNT (*) from GroupInfo
<trim prefix= "WHERE" prefixoverrides= "And|or" > and ID in <foreach collection= "Idstr" item= " 
IDs" open= "(" Separator= "," close= ")" > 
#{ids} 
</foreach> 
<if test= "name!= null and name!=" "> and
Name like CONCAT (CONCAT ('% ', #{name}), '% ')
</if>
<if test= ' description!= null and description!= ' " gt;
and description like CONCAT (CONCAT ('% ', #{description}), '% ')
</if>
<if test= ' type!= null and type!=  -1 "> and
type = #{type,jdbctype=integer}
</if>
<if test=" category!= null and Category!=-1 > and
category = #{category,jdbctype=integer}
</if>
</trim> 
</select>

Java code:

Gets the total number of child group records public
int Selectchildgrouptotalnum (map<string, object> recordmap); 
map<string, object> recordmap = new hashmap<string, object> ();
Recordmap.put ("Idstr", Group.getchildgroupids (). Split (","));
Recordmap.put ("name", name);
Recordmap.put ("description", description);
Recordmap.put ("type",-1);
Recordmap.put ("category",-1);
Childgrouptotalnum = Groupdao.selectchildgrouptotalnum (Recordmap);

④ Multiple parameters:

Method One: Pass parameters in order.

<!--query parameters based on parameter name-->
<select id= "Selectsensornobysensorname" resulttype= "Integer" usecache= "false" Flushcache= "true" >
select Sensorno from Sensorconfig 
where Name = #{0} and Testunitno = #{1} and Labcode = #{ 2}
</select>

Java code:

Query parameter ID public
int selectsensornobysensorname (string sensorname, int testunitno, string labcode) based on parameter names;

Method Two: Add @param annotation on interface parameter.

<select id= "Selectbyusernameandvcode" resultmap= "Userbaseresultmap" >
select ID, userName from user
<trim prefix= "WHERE" prefixoverrides= "And|or" >
<if test= "username!= null and username!=" "> and
UserName like CONCAT (CONCAT ('% ', #{username}), '% ')
</if>
<if test= ' supplierno!= null and supplierno! = ' "> and
supplierno like CONCAT (CONCAT ('% ', #{supplierno}), '% ')
</if> and 
supplierno!= ' Test '
</trim>
LIMIT #{startindex},#{pagesize}
</select>

Java code:

Query user information based on username and V
list<user> selectbyusernameandvcode (
@Param ("UserName") String UserName,
@Param ("Supplierno") String Supplierno,
@Param ("startIndex") int startIndex, @Param ("pageSize") int pageSize );

4 Dynamic SQL statement:

Selectkey label, if tag, if + where condition is judged, if + Set UPDATE statement, if + trim replaces Where/set label, Trim replaces Set,choose (when, otherwise), foreach tag. Dynamic SQL statement is the most flexible part of the mybatis, it is very convenient to use.

Example: Selecttotalnumbyaccounttype

<select id= "Selecttotalnumbyaccounttype" resulttype= "Integer" >
Select COUNT (*) from user
<trim prefix= "WHERE" prefixoverrides= "And|or" > and ID not in <foreach collection= "Idstr" item= " 
IDs" open= "(" Separator= "," close= ")" > 
#{ids} 
</foreach> 
<if test= "username!= null and username!=" ">
and UserName like CONCAT (CONCAT ('% ', #{username}), '% ')
</if>
<if test= ' supplierno!= null and Supplierno!= ' ">
and Supplierno like CONCAT (CONCAT ('% ', #{supplierno}), '% ')
</if> 
<if Test= "truename!= null and truename!=" ">
and Truename like CONCAT (CONCAT ('% ', #{truename}), '% ')
</if > and
accounttype = #{accounttype}
</trim></select>

The above is small set to introduce the MyBatis persistence layer framework of the use of knowledge summary, I hope to help you, if you have any questions please give me a message, small set will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.