In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article shares with you the content of a sample analysis of XML mapping profiles in MyBatis. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
My Batis supports SQL queries and is a perfect demonstration of some high-level mappings in the persistence layer. He uses more simple XML or annotations for configuration and original mapping, eliminating a lot of JDBC code, manually setting parameters and result set encapsulation, and improving development efficiency.
MyBatis's XML configuration file contains settings and property information that have a profound impact on MyBatis behavior. The high-level structure of the XML document is as follows:
Configuration configuration
Environment environment variable
TransactionManager transaction Manager
DataSource data source
Properties attribute
Settings Settin
TypeAliases type naming
TypeHandlers type processor
ObjectFactory object Factory
Plugins plug-in
Environments environment
Mapper
The following is a detailed description of each attribute configuration.
Properties
These are externalized, replaceable attributes that can also be configured in a typical Java attribute configuration file or passed through child elements of the properties element.
For example:
[html] view plain copy [html] view plain copy
The username and password in this example will be replaced by the values set in the properties element. The driver and url attributes will be replaced from the values in the included jdbc_mysql.properties file.
Settings
These are extremely important adjustments that modify the way MyBatis behaves at run time. The following table describes the settings information, their meaning, and default values.
Set parameter description
CacheEnabled this configuration causes the global mapper to enable or disable caching.
LazyLoadingEnabled enables or disables deferred loading globally. When off, all associated objects are loaded immediately.
When aggressiveLazyLoading is enabled, objects with deferred load properties will fully load arbitrary properties when called. Otherwise, each property will be loaded as needed.
MultipleResultSetsEnabled allows or disallows multiple result sets to be returned from a single statement (appropriate driver is required).
UseColumnLabel uses column labels instead of column names. Different drivers behave differently in this convenience. Refer to the driver documentation or fully test both methods to determine which driver to use.
UseGeneratedKeys allows JDBC to support generated keys. A suitable driver is needed. If set to true, this setting forces the generated key to be used, and some drivers are still valid even though they are not compatible (such as Derby).
AutoMappingBehavior specifies how MyBatis automatically maps columns to fields / attributes. PARTIAL will only automatically map simple, no nested results. FULL automatically maps arbitrarily complex results (nested or otherwise).
DefaultExecutorType configures the default actuator. There is nothing special about SIMPLE actuators. The REUSE executor reuses preprocessing statements. BATCH executor reuse statements and batch updates
DefaultStatementTimeout sets the timeout, which determines how long the driver waits for a database response.
An example of setting information elements, the full configuration is as follows:
TypeAliases
A type alias is a short name for the Java type. It is only relevant to the XML configuration and is only used to reduce the excess of the fully qualified name of the class. For example:
[html] view plain copy [html] view plain copy
With this configuration, "Blog" can be used as an alternative to where "domain.blog.Blog" is used.
TypeHandlers
Whether MyBatis sets a parameter in a preprocessing statement or fetches a value from the result set, the type handler is used to convert the obtained value to the Java type in an appropriate manner. The following list describes the default type handlers. Type processor Java type JDBC type in turn
BooleanTypeHandler Boolean,boolean any compatible Boolean value
ByteTypeHandler Byte,byte any compatible numeric or byte type
ShortTypeHandler Short,short any compatible digits or short integers
IntegerTypeHandler Integer,int any compatible numbers and integers
LongTypeHandler Long,long any compatible numbers or long integers
FloatTypeHandler Float,float any compatible digital or single-precision floating-point type
DoubleTypeHandler Double,double any compatible digital or double-precision floating-point type
BigDecimalTypeHandler BigDecimal any compatible numeric or decimal decimal type
StringTypeHandler String CHAR and VARCHAR types
ClobTypeHandler String CLOB and LONGVARCHAR types
NStringTypeHandler String NVARCHAR and NCHAR types
NClobTypeHandler String NCLOB Typ
ByteArrayTypeHandler byte [] any compatible byte stream type
BlobTypeHandler byte [] BLOB and LONGVARBINARY types
DateTypeHandler Date (java.util) TIMESTAMP type
DateOnlyTypeHandler Date (java.util) DATE type
TimeOnlyTypeHandler Date (java.util) TIME type
SqlTimestampTypeHandler Timestamp (java.sql) TIMESTAMP type
SqlDateTypeHandler Date (java.sql) DATE type
SqlTimeTypeHandler Time (java.sql) TIME type
ObjectTypeHandler Any other or unspecified type
EnumTypeHandler Enumeration type VARCHAR- any compatible string type, stored as code (not an index).
ObjectFactory
Each time MyBatis creates a new instance of the resulting object, it uses an instance of ObjectFactory. If a parameter mapping exists, the default ObjectFactory does no more than instantiating the target class using the default constructor or constructor with parameters.
Plugins
MyBatis allows you to intercept calls executed by mapped statements at some point. By default, MyBatis allows the use of plug-ins to intercept method calls:
Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed) ParameterHandler (getParameterObject, setParameters) ResultSetHandler (handleResultSets, handleOutputParameters) StatementHandler
(prepare, parameterize, batch, update, query)
The details of the methods in these classes can be found by looking at the signature of each method, and their source code is available in the MyBatis distribution. You should understand the behavior of overriding methods, assuming that you are doing more than monitoring calls. If you try to modify or override a given method, you may break the core of MyBatis. These are low-level classes and methods, and plug-ins should be used with caution.
Using plug-ins is the very simple power they provide. Simply implement the interceptor interface to determine the specified signature you want to intercept.
Java Code:
[javascript] view plain copy@Intercepts ({@ Signature (type= Executor.class,method = "update", [javascript] view plain copyargs = {MappedStatement.class,Object.class})) [javascript] view plain copypublic class ExamplePlugin implements Interceptor {[javascript] view plain copypublic Object intercept (Invocation invocation) throws Throwable [javascript] view plain copy {[javascript] view plain copyreturn invocation.proceed (); [javascript] view plain copy} [javascript] view plain copypublic Object plugin (Object target) {[javascript] view plain copyreturn Plugin.wrap (target, this) [javascript] view plain copy} [javascript] view plain copypublic void setProperties (Properties properties) {[javascript] view plain copy} [html] view plain copyMapperConfig.xml [html] view plain copy [html] view plain copy
The above plug-in will intercept all "update" method calls in the Executor instance, which is also the internal object responsible for the execution of low-level mapping statements.
Environments
[html] view plain copy dataSsource
The dataSource element uses the basic JDBC data source interface to configure the resources of the JDBC connection object. See above
TransactionManager
There are two types of transaction managers in MyBatis (that is, type= "[JDBC | MANAGED]"):
1.JDBC-this configuration simply uses JDBC's commit and rollback settings. It relies on connections from the data source to manage the transaction scope.
2.MANAGED-this configuration does little. It never submits or rolls back a connection. It allows the container to manage the entire lifecycle of the transaction (such as the context of the Spring or JEE application server). By default, it closes the connection. However, some containers don't want this, so if you need to stop it from the connection, set the closeConnection property to false. For example:
[html] view plain copy
Neither of these transaction managers requires any attributes. However, they are all type aliases, and to replace them, you need to place the fully qualified name or type alias of your own class, which refers to your implementation class to the TransacFactory interface.
Public interface TransactionFactory {
Void setProperties (Properties props)
Transaction newTransaction (Connection conn, boolean autoCommit)
}
Any properties configured in XML will be passed to the setProperties () method after instantiation. Your implementation class needs to create an implementation of a transaction interface, which is also very simple:
[html] view plain copypublic interface Transaction {Connection getConnection (); void commit () throws SQLException; void rollback () throws SQLException; void close () throws SQLException;}
Using these two interfaces, you can completely customize how MyBatis handles transactions.
Mappers
Now that the behavior of MyBatis has been configured by the above elements, we now need to define the SQL mapping statement. But first we need to tell MyBatis where to find these statements. Java doesn't provide a good way to do this, so the best way is to tell MyBatis where to find the mapping file. You can use the resource reference relative to the classpath, or the character representation, or the fully qualified name of the url reference (including file:///URLs). For example:
[html] view plain copy// Using classpath relative resources (preferred) / / Using url fully qualified paths Thank you for your reading! This is the end of the article on "sample analysis of XML mapping configuration files in MyBatis". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.