MyBatis Framework Execution Process:
1, configuration mybatis configuration file, Sqlmapconfig.xml (name is not fixed)
2, through the configuration file, load MyBatis running environment, create sqlsessionfactory session factory
Sqlsessionfactory in the actual use of a single case way.
3, through Sqlsessionfactory to create sqlsession
Sqlsession is a user interface (provides operation database method), implementation object is thread unsafe, suggest sqlsession application in the method body.
4, call the Sqlsession method to manipulate the data.
If you need to commit a transaction, you need to perform a sqlsession commit () method.
5, release resources, close sqlsession
Mapper Agent Development Method (recommended)
Programmers are only required to write mapper interfaces (that is, DAO interfaces)
Programmers need to follow a development specification in writing mapper.xml (mapping files) and Mapper.java:
1, Mapper.xml namespace is the Mapper.java class full path.
2, Mapper.xml in the statement ID and Mapper.java in the same method name.
3, the parametertype of the statement in Mapper.xml specifies the type of input parameter and the Mapper.java method input parameter type.
4, the Resulttype of the statement in Mapper.xml specifies the type of the output result and the Mapper.java method return value type.
Article content:
The order commodity data model is analyzed.
Advanced Mapping: (understanding)
To achieve one-to-one query, One-to-many, many-to-many query.
Deferred loading
Query caching
First-level caching
Second-level caching (understanding MyBatis level Two cache usage scenarios)
MyBatis and SPIRNG Integration (mastery)
Reverse engineering (to be used)
Order Commodity Data Model
The thought of data model analysis
1, each table records the data content
The module is familiar with the contents of each table, which is equivalent to the process of learning system requirements (functions).
2. Important field settings for each sheet
Non-empty field, foreign key field
3, database Level table and the relationship between tables
FOREIGN key relationship
4, the table and the business relationship between the table
The analysis of the business relationship between tables and tables must be based on a business sense.
Data Model Analysis
Users table User:
Record the user information for the purchase of the product
Order Form: Orders
Record the order created by the user (purchase order for the item)
Order list: OrderDetail:
The details of the order are recorded, that is, the purchase of the goods
Product List: Items
Recorded the product information
Business relationship Between tables:
Analysis of the business relationship between tables and tables needs to be based on a business sense.
First, analyze the business relationships between tables that have relationships between data levels:
Usre and Orders:
User-->orders: A user can create multiple orders, One-to-many
Orders->user: An order is created by only one user, one-to-one
Orders and OrderDetail:
Orders–> OrderDetail: An order can include multiple order details, because one order can buy multiple items, purchase information for each item in OrderDetail record, one-to-many relationship
Orderdetail–> Orders: An order detail can only be included in one order, one-to-one
OrderDetail and ITESM:
Orderdetail-> itesms: One order detail corresponds to only one commodity information, one-to-one
Items–> OrderDetail: A product can be included in multiple order details, a pair of many
Re-analyze whether there is a business relationship between tables that have no relationship to the database level:
Orders and items:
A relationship can be established between orders and items through the OrderDetail table.
User and items: multiple pairs of relationships are formed through other tables
One-to-one query
Requirements: Query order information, associated query create the user information of the order
Query using the Resulttype method
SQL Statement Usage considerations
To determine the primary table for a query: Order table
Determining the associated table for a query: User table
is the associated query using internal or external links?
Because there is a foreign key (USER_ID) in the Orders table, querying the user table through a foreign key association can only query out one record and use the inner link.
SELECT
orders.*,
user.username,
user.sex,
user.address
from
orders,
USER
WHERE orders.user_id = user.id
Create Pojo (Orderscustom.java)
The results of the top SQL query are mapped to Pojo, and all query column names must be included in Pojo.
The original Orders.java cannot map all the fields, and a newly created Pojo is required.
Create a Pojo inheritance includes the PO classes with more query fields.
Ordersmappercustom.xml
Ordersmappercustom.java
Writing test Classes
Select Ordersmappercustom.java file Right-–> select new–>others–> Junit Test case–> Select the function to test
Write the following code in Ordersmappercustomtest.java:
public class Ordersmappercustomtest {
private sqlsessionfactory sqlsessionfactory;
This method is performed
@Before public
void SetUp () throws Exception {
//create Sqlsessionfactory
before executing Testfinduserbyid MyBatis configuration file
String resource = "Sqlmapconfig.xml";
Get configuration file stream
inputstream inputstream = resources.getresourceasstream (Resource);
Create session factory, pass in MyBatis profile information
sqlsessionfactory = new Sqlsessionfactorybuilder (). Build (InputStream);
@Test public
void Testfindordersuser () throws Exception {
sqlsession sqlsession = Sqlsessionfactory.opensession ();
Create a proxy object
ordersmappercustom ordersmappercustom = sqlsession
. Getmapper (ordersmappercustom.class);
Call Maper method
list<orderscustom> List = Ordersmappercustom.findordersuser ();
SYSTEM.OUT.PRINTLN (list);
Sqlsession.close ();
}
Query using the Resultmap method
SQL statements: SQL implemented with Resulttype
The idea of using RESULTMAP mapping
Use Resultmap to map the order information in the query results to the Orders object, add the user attribute to the orders class, and map the user information from the associated query into the user attribute in the Orders object.
Add user property to the Orders class
Ordersmappercustom.xml
Define Resultmap
Tyep: Indicates that the result of the entire query is mapped to a class eg:cn.itcast.mybatis.po.Orders
ID: The unique identification of the query column in the database table, the unique identification in the order information, if multiple columns make up a unique identity, configuring multiple IDs
Column: Unique identifying columns for order information in a database table
Property: The unique identity column for the order information is mapped to which attribute in the orders
Association: Information used to map a single object for an associated query
Property: To map the user information of the associated query to which attribute in orders
Javatype: Which attribute is mapped to user
<!--order Query the Resultmap of the associated user maps the results of the entire query to Cn.itcast.mybatis.po.Orders--> <resultmap type= " Cn.itcast.mybatis.po.Orders "id=" Ordersuserresultmap > <!--configuration map order information--> <!--ID: Specifies the unique identifier in the query column, the only in the order information ID, if multiple columns make up a unique identity, configure multiple ID columns: Unique identity column property for order information: The unique identity column for order information is mapped to which attribute in orders--> <id column= "id" property= "id" /> <result column= "user_id" property= "UserId"/> <result column= "number" property= "number"/> <result Column= "Createtime" property= "Createtime"/> <result "Note" Column= <!--the associated user information for the configuration map- > <!--Association: Information property for mapping a single object for an associated query: to map the user information of the associated query to which attribute--> <association property= "user" in orders
Javatype= "Cn.itcast.mybatis.po.User" > <!--ID: The unique identity of the associated query user column: Specifies the column javatype that uniquely identifies the user's information: which property is mapped to users--> <id column= "user_id" property= "IDs"/> <result column= "username" property= "username"/> <result column= " Sex "property=" sex "/> <result column=" Address "property=" Address "/> </associatioN> </resultMap>
Statement definition
Ordersmappercustom.java
Test code
@Test public
void Testfindordersuserresultmap () throws Exception {
sqlsession sqlsession = Sqlsessionfactory.opensession ();
Create a proxy object
ordersmappercustom ordersmappercustom = sqlsession
. Getmapper (ordersmappercustom.class);
Call Maper method
list<orders> List = Ordersmappercustom.findordersuserresultmap ();
SYSTEM.OUT.PRINTLN (list);
Sqlsession.close ();
}
Resulttype and Resultmap implement one-to-one query summary
Resulttype: Using the Resulttype implementation is simpler, if the Pojo does not include the query out of the column name, you need to increase the column name corresponding to the property, you can complete the mapping.
Resulttype is recommended if there are no special requirements for query results.
Resultmap: Need to define the RESULTMAP, the implementation is a bit cumbersome, if there are special requirements for query results, using RESULTMAP can be completed to map the associated query Pojo properties.
Resultmap can implement deferred loading, Resulttype cannot implement deferred loading.
One-to-many Query
Requirements: Search for information on orders and order details.
SQL statement
Determine the main query table: Order table
To determine the associated query table: Order Schedule
Add an order BOM association on a one-to-one query basis.
SELECT
orders.*,
user.username,
user.sex,
user.address,
orderdetail.id orderdetail_id,
orderdetail.items_id,
orderdetail.items_num,
orderdetail.orders_id
from
orders,
USER,
OrderDetail
WHERE orders.user_id = user.id and Orderdetail.orders_id=orders.id
Analysis: Using Resulttype to map the query results above to Pojo, the order information is duplicated.
Requirement: Duplicate records cannot occur on orders mappings.
Add the List<orderdetail> OrderDetails property to the Orders.java class.
The order information is eventually mapped to orders, and the order details for the order are mapped to the OrderDetails attribute in orders.
The number of orders to be mapped to two (orders information does not repeat)
The OrderDetails property in each orders stores the order details for the order.
Add list Order Detail properties in Orders.java
Ordersmappercustom.xml
Resultmap definition
Use extends inheritance without having to configure the mapping of order information and user information in
Collection: Mapping associated queries to multiple records in a collection object
Property: Maps an associated query to multiple records to cn.itcast.mybatis.po.Orders which attribute
OfType: Specifies the type of Pojo mapped to the List collection property
<!--orders and order Details Resultmap
use extends inheritance without having to configure the mapping of order information and user information in
-->
<resultmap type= " Cn.itcast.mybatis.po.Orders "id=" Ordersandorderdetailresultmap "extends=" Ordersuserresultmap ">
<!-- Order Information-->
<!--user information-->
<!--use extends inheritance without having to configure the mapping of order information and user information in-->
<!--order
details An order association query out of a number of details, to use collection mapping
collection: Associated query to more than one record map to the collection object
Property: Maps an associated query to multiple records to cn.itcast.mybatis.po.Orders which attribute
OfType: Specifies the type that maps to Pojo in the list collection Properties
-->
< Collection property= "OrderDetails" oftype= "Cn.itcast.mybatis.po.Orderdetail" >
<!--ID: Order Details Unique identification
Property: To map the unique identification of the order details to which of the Cn.itcast.mybatis.po.Orderdetail properties
-->
<id column= "orderdetail_id" property= "id"/>
<result column= "items_id" property= "Itemsid"/> <result "column="
property= "Itemsnum"/>
<result column= "orders_id" property= "Ordersid"/>
</collection>
</resultMap>
Ordersmappercustom.java
Test code:
@Test public
void Testfindordersandorderdetailresultmap () throws Exception {
sqlsession sqlsession = Sqlsessionfactory.opensession ();
Create a proxy object
ordersmappercustom ordersmappercustom = sqlsession
. Getmapper (ordersmappercustom.class);
The method to invoke Maper
list<orders> List = Ordersmappercustom
. Findordersandorderdetailresultmap ();
SYSTEM.OUT.PRINTLN (list);
Sqlsession.close ();
}
Summary
MyBatis uses Resultmap's collection to map multiple records of an associated query to a list collection property.
Using Resulttype implementation:
Map the order details to orders in the OrderDetails, you need to deal with, use double loop traversal, remove duplicate records, put order details in the OrderDetails.
Multiple to multiple query
Requirements: Inquires the user and the user buys the commodity information.
SQL statement
Query Main Table is: User table
Association table: Because the user and the goods are not directly related, through the order and order details related, so the association table: orders, OrderDetail, items
SELECT
orders.*,
user.username,
user.sex,
user.address,
orderdetail.id orderdetail_id,
orderdetail.items_id,
orderdetail.items_num,
orderdetail.orders_id,
items.name items_name,
Items.detail Items_detail,
items.price items_price
from
orders,
USER,
OrderDetail,
Items
WHERE orders.user_id = User.ID and orderdetail.orders_id=orders.id and orderdetail.items_id = Items.id
Mapping ideas
Maps user information to users.
Add order list properties to the user class list<orders> orderslist to map user-created orders to Orderslist
Add Order Detail List attribute list<orderdetail>orderdetials to orders, map details of order to Orderdetials
Add the Items property to the OrderDetail to map the items corresponding to the order details to item
Ordersmappercustom.xml
Resultmap definition
<!--inquiries users and purchased merchandise--> <resultmap type= "Cn.itcast.mybatis.po.User" id= "Useranditemsresultmap" > <!--User Information- -> <id column= "user_id" property= "id"/> <result column= "username" property= "username"/> <result column= "Sex" property= "sex"/> <result column= "Address" property= "Address"/> <!--order Information A user corresponds to multiple orders, Using collection mapping--> <collection property= "orderslist" oftype= "cn.itcast.mybatis.po.Orders" > <id column= " ID "property=" id "/> <result column=" user_id "property=" UserId "/> <result column=" number "property=" number "/> <result column=" createtime "property=" Createtime "/> <result column=" Note "property=" note "/> <!- -Order Details One order includes multiple details--> <collection property= "OrderDetails" oftype= "Cn.itcast.mybatis.po.Orderdetail" > <id Column= "orderdetail_id" property= "id"/> <result column= "items_id" property= "Itemsid"/> <result "column=" Items_num "property=" Itemsnum "/> <result column=" orders_id "property=" orDersid "/> <!--commodity information an order detail corresponds to a commodity--> <association property=" items "javatype=" Cn.itcast.mybatis.po.Items " > <id column= "items_id" property= "id"/> <result "column= items_name" property= "name"/> <result column
= "Items_detail" property= "detail"/> <result column= "Items_price" property= "Price"/> </association> </collection> </collection> </resultMap>
Ordersmappercustom.java
Test code:
@Test public
void Testfinduseranditemsresultmap () throws Exception {
sqlsession sqlsession = Sqlsessionfactory.opensession ();
Create a proxy object
ordersmappercustom ordersmappercustom = sqlsession
. Getmapper (ordersmappercustom.class);
Call Maper method
list<user> List = Ordersmappercustom.finduseranditemsresultmap ();
SYSTEM.OUT.PRINTLN (list);
Sqlsession.close ();
}
multiple to multiple query summary
Will inquire the user to purchase the commodity information detailed list, (user name, user address, purchase commodity name, purchase commodity time, purchase quantity of goods)
For the requirements above, using Resulttype to map the query to an extended Pojo, it is very simple to implement the function of the detail list.
One-to-many is a special case of Many-to-many, as follows:
Query user purchase information, user and commodity relationship is a many-to-many relationship.
Demand 1:
Query fields: User account, user name, user sex, commodity name, commodity price (most common)
Common Detail list in enterprise development, user purchase detail list,
Use Resulttype to map the top query column to the Pojo output.
Demand 2:
Query fields: User account, user name, purchase quantity, merchandise details (mouse over display details)
Use Resultmap to map the list of itemized items purchased by the user to the Users object.
Summarize:
The use of Resultmap is for those features that have special requirements for mapping query results, such as special requirements mapped into lists that include multiple lists.
Summary of Resulttype and Resultmap
Resulttype:
Role:
The query results are mapped to Pojo in accordance with the SQL column name Pojo property name consistency.
Occasion:
Some common details of the display of records, such as the user purchase details, will be associated with the query information all displayed in the page, at this time can be directly used resulttype each record map
Into the Pojo, in the front page traversal list (list is Pojo) can be.
Resultmap:
Complete one-to-one and One-to-many advanced Mappings with Association and collection (special mapping requirements for results).
Association:
Role:
Maps the associated query information to a Pojo object.
Occasion:
To facilitate Query association information, you can use association to map the associated order information to the Pojo attribute of the user object, such as: query order and associated user information.
Using Resulttype, you cannot map query results to the Pojo properties of Pojo objects, choosing whether to use Resulttype or Resultmap depending on the needs of the query traversal for the result set.
Collection
Role:
Maps the associated query information to a list collection.
Occasion:
In order to facilitate the query traversal correlation information can use collection to map the correlation information to the list collection, for example: Query user permission scope module and the menu under the module, can use collection to map the module to the module list, Map the menu list to the Menu list property of the module object, which is designed to facilitate traversal queries on the query result set.
If you use Resulttype, you cannot map query results to the list collection.
Deferred loading
Resultmap can implement advanced Mapping (using association, collection to achieve one-to-one and one-to-many mappings), association, and collection have deferred loading capabilities.
Demand:
If the order is queried and the query user information is associated. If you first query the order information to meet the requirements, when we need to query the user information and then query the user information. The need to query the user information is deferred loading.
Delay loading: First from a single table query, and then from the associated table to correlate the query, greatly improve the performance of the database, because the query list than the associated query more than a table faster.
Using Association to implement deferred loading
Requirements: Search for orders and correlate query user information
Ordresmappercustom.xml
You need to define two mapper methods corresponding to the statement.
1. Query Order information only
Use Association to delay loading (execute) The satatement below in query order statement (associated query user information)
2, the association inquires the user information
user_id to correlate query user information through the order information that is queried above
Using the Finduserbyid in Usermapper.xml
Top to perform findordersuserlazyloading, when you need to query the user to execute the Finduserbyid, through the definition of RESULTMAP will delay load execution configuration.
Deferred load Resultmap
Use the Select in association to specify the ID of the statement to execute with deferred loading.
<!--delay-loaded resultmap-->
<resultmap type= "cn.itcast.mybatis.po.Orders" id= " Ordersuserlazyloadingresultmap ">
<!--Map the order information to configure-->
<id column=" id "property=" id "/>
<result column= "user_id" property= "UserId"/> <result column= "number
" property= "number"/>
< Result column= "Createtime" property= "Createtime"/> <result column= ' note
' property= "note"/>
-Implement deferred loading of user information
Select: Specifies the ID of the statement to be executed for deferred loading (is the statement that queries user information based on user_id)
To use Finduserbyid in Usermapper.xml to complete a query based on user ID (user_id) user information, if Finduserbyid is not required in this mapper, the front plus namespace
Column: The columns of the query for the associated user information in the order information are user_id
The SQL of the associated query is understood to be:
Select orders.*,
(select username from user where orders.user_id = user.id) Username,
(select sex from user where O rders.user_id = user.id) Sex from
orders
-->
<association property= "user" javatype= " Cn.itcast.mybatis.po.User "
select=" cn.itcast.mybatis.mapper.UserMapper.findUserById "column=" user_id ">
<!--implement delayed loading of user information-->
</association>
</resultMap>
Orderesmappercustom.java
Test ideas:
1, the implementation of the top Mapper method (findordersuserlazyloading), Internal to call Cn.itcast.mybatis.mapper.OrdersMapperCustom in the findordersuserlazyloading only query orders information (single table).
2, in the program to traverse the previous step query out of the LIST<ORDERS>, and when we call the GetUser method in the Orders, we begin to delay loading.
3, delay loading, to call Usermapper.xml Finduserbyid This method to obtain user information.
Deferred load configuration
MyBatis does not turn on delay loading by default and requires setting configuration in Sqlmapconfig.xml.
Configured in the MyBatis core configuration file:
Set Item description allowable value default value
lazyloadingenabled global setting lazy load. If set to ' false ', all associated will be initialized to load. True or False
Aggressivelazyloading when set to ' true ', lazy loaded objects may be loaded by any lazy attributes. Otherwise, each property is loaded on demand. True or False true
Configure in Sqlmapconfig.xml:
Test code
Deferred load thinking
How do I implement deferred loading without using the deferred loading feature in the association and collection provided by MyBatis?
The implementation method is as follows:
Define two mapper methods:
1. Search Order List
2, according to User ID query user information
Realize the idea:
First to query the Mapper method, get order Information list
In the program (service), on demand to call the second Mapper method to query the user information.
In short: Use the deferred Load method, first to query simple SQL (best single table, can also be associated with the query), and then to load the associated query as needed other information.
Query caching
MyBatis provides query caching to reduce data pressure and improve database performance.
Mybaits provides a first-level cache, and a level two cache.
The first level cache is the sqlsession level cache. The Sqlsession object needs to be constructed when manipulating the database, and there is a data structure (HASHMAP) in the object to store the cached data. The cached data regions (HASHMAP) between different sqlsession are not affected by each other.
Second-level caching is the mapper level of caching, multiple sqlsession to operate the same mapper SQL statements, multiple sqlsession can share a level two cache, level two cache is cross sqlsession.
Why should I use caching?
If there is data in the cache that does not need to be retrieved from the database, it greatly improves system performance.
First-level caching
How the first level of caching works
The first time to query user ID 1 user information, first to find out whether the cache has ID 1 user information, if not, from the database query user information.
The user information is obtained and the user information is stored in the first level cache.
If sqlsession to perform a commit (INSERT, UPDATE, delete), empty the first level cache in the sqlsession, the purpose of this is to keep the current information stored in the cache and avoid dirty reads.
The second launch query user ID 1 user information, first to find out whether the cache has ID 1 user information, the cache has, directly from the cache to obtain user information.
First-level cache test
The MyBatis default supports a level one cache and does not need to be configured in the configuration file.
Follow the top level caching principle steps to test.
Ordersmappercusntomtest.java
@Test public
void TestCache1 () throws exception{
sqlsession = Sqlsessionfactory.opensession ()//Create proxy object
usermapper usermapper = Sqlsession.getmapper (usermapper.class);
The bottom query uses a sqlsession
//First request, a user with a query ID of 1
user1 = Usermapper.finduserbyid (1);
System.out.println (user1);
If sqlsession to perform a commit (INSERT, UPDATE, delete), empty the first level cache in the sqlsession, the purpose of this is to keep the current information stored in the cache and avoid dirty reads.
//Update user1 information
user1.setusername ("Test user");
Usermapper.updateuser (user1);
Perform a commit operation to empty the cache
sqlsession.commit ();
Second launch request, user
user2 = Usermapper.finduserbyid (1) with Query ID 1;
System.out.println (user2);
Sqlsession.close ();
}
First-level caching applications
Formally developed, the MyBatis and spring are integrated and developed, and transactions are controlled in service.
A service method includes many Mapper method calls.
service{
//When executing, open transaction, create sqlsession object
//First Call mapper method Finduserbyid (1)
//Second Call mapper method Finduserbyid ( 1), from the first cache to fetch data
//method end, sqlsession close
}
If you are performing two service call query the same user information, do not go to the first level of caching, because the session method ends, the sqlsession is closed, the first cache is emptied.
Second-level caching
Principle
First, open the MyBatis level two cache.
SqlSession1 to query User ID 1 user information, query to user information will be the query data stored in level two cache.
If SqlSession3 to execute the same mapper SQL, perform a commit commit and empty the data in the level two cache area under the mapper.
SqlSession2 to query User ID 1 user information, to the cache to find whether there is data, if there is a direct extraction of data from the cache.
The second-level cache differs from the first-level cache in that the level two cache is larger and multiple sqlsession can share a usermapper two-level cache region.
Usermapper has a level two cache area (by namespace), and other mapper also have their own level two cache area (by namespace).
Each namespace mapper has a two cache area, two mapper namespace if the same, the two mapper execute the SQL query to the data will exist in the same level two cache area.
Turn on level two cache
Mybaits's Level Two cache is mapper range level, in addition to setting the total switch of level two cache in Sqlmapconfig.xml, and opening a level two cache in a specific mapper.xml.
Adding in the core configuration file Sqlmapconfig.xml
<setting name= "cacheenabled" value= "true"/>
Describe allowable values default values
Cacheenabled the global on/off setting for all cache under this profile. True or False
In Usermapper.xml, the level two cache is turned on, and the completion of SQL execution in Usermapper.xml is stored in its cache area (HASHMAP).
Calling the Pojo class to implement the serialization interface
In order to take the cached data out to perform deserialization operations, because the level two cache data storage media varies in memory.
Second-level cache test
@Test public
void TestCache2 () throws Exception {
sqlsession sqlSession1 = sqlsessionfactory.opensession ();
Sqlsession SqlSession2 = Sqlsessionfactory.opensession ();
Sqlsession SqlSession3 = Sqlsessionfactory.opensession ();
Create a proxy object
usermapper userMapper1 = Sqlsession1.getmapper (usermapper.class);
The first time the request was initiated, the user
user1 = Usermapper1.finduserbyid (1) with a query ID of 1;
System.out.println (user1);
The shutdown operation is performed here, and the data in the sqlsession is written to the level two cache area
sqlsession1.close ();
Use SqlSession3 to perform a commit () operation
Usermapper UserMapper3 = Sqlsession3.getmapper (usermapper.class);
User user = Usermapper3.finduserbyid (1);
User.setusername ("Ms Cheung");
Usermapper3.updateuser (user);
Execute the submission, emptying the level two cache
Sqlsession3.commit () below the usermapper;
Sqlsession3.close ();
Usermapper userMapper2 = Sqlsession2.getmapper (usermapper.class);
Second launch request, user
user2 = Usermapper2.finduserbyid (1) with Query ID 1;
System.out.println (user2);
Sqlsession2.close ();
}
UseCache Configuration
Setting Usecache=false in statement can disable the level two cache of the current SELECT statement, that is, each query emits SQL to query, the default is true, that is, the SQL uses level two caching.
<select id= "Findorderlistresultmap" resultmap= "Ordersusermap" usecache= "false" >
Summary: For each query requires the latest data SQL, to set to Usecache=false, disable level two cache.
Flush Cache
is to empty the cache.
In the same namespace of mapper, if you have additional insert, UPDATE, delete operation data, you need to flush the cache, and dirty reads occur if you do not perform a refresh cache.
Set the Flushcache= "true" property in the statement configuration, which is true to flush the cache by default, and not if it is changed to false. Dirty reads occur when you use caching to manually modify query data in a database table.
<insert id= "Insertuser" parametertype= "Cn.itcast.mybatis.po.User" flushcache= "true" >
Summary: Generally, performing a commit requires refreshing the cache, and flushcache=true means refreshing the cache, which avoids database dirty reads.
MyBatis Integration Ehcache
Ehcache is a distributed caching framework.
Distribution Cache
Our system in order to improve system concurrency, performance, general distributed deployment of the system (cluster deployment mode)
Without the use of distributed caching, cached data is stored separately in each service and is not convenient for system development. Therefore, the cached data is centrally managed using distributed caching.
MyBatis cannot implement distributed caching and needs to be integrated with other distributed caching frameworks.
Integrated Ehcache method (master)
MyBatis provides a cache interface, if you want to implement their own caching logic, implementation of cache interface development.
MyBatis and Ehcache integration, MyBatis and Ehcache consolidation packages provide an implementation class for the cache interface.
MyBatis default Implementation Cache class is:
Add Ehcache Package
Integrated Ehcache
Configure the type in cache in Mapper as the implementation of the cache interface for Ehcache.
Join Ehcache configuration file (Configure Ehcache.xml under Classpath)
<ehcache xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
xsi:nonamespaceschemalocation= ". /config/ehcache.xsd ">
<diskstore path=" F:\develop\ehcache "/>
<defaultcache
maxelementsinmemory= "1000"
maxelementsondisk= "10000000"
eternal= "false"
overflowtodisk= "false" Timetoidleseconds= "timetoliveseconds=" and "
diskexpirythreadintervalseconds=
" memorystoreevictionpolicy= "LRU" >
</defaultCache>
</ehcache>
Attribute Description:
Diskstore: Specifies where the data is stored on the disk.
Defaultcache: When the cache is created with Cachemanager.add ("Democache"), Ehcache takes the <defalutCache/>-specified management policy
The following properties are required:
Maxelementsinmemory-The maximum number of element buffers in memory
Maxelementsondisk-The maximum number of element caches on disk, if 0 indicates infinity
Eternal-Sets whether the cached elements will never expire. If true, the cached data is always valid and, if False, based on the Timetoidleseconds,timetoliveseconds judgment
Overflowtodisk-Sets whether expired element is cached on disk when the memory cache overflows
The following properties are optional:
Timetoidleseconds-This data is deleted when the time before and after two accesses to the data in Ehcache exceeds the Timetoidleseconds property value, and the default value is 0, which is idle time infinity
Timetoliveseconds-The valid lifetime of the cache element, the default is 0, which is the element survival time Infinity
Diskspoolbuffersizemb This parameter sets the buffer size of the Diskstore (disk cache). The default is 30MB. Each cache should have a buffer of its own.
Diskpersistent-Enables the disk to save the data in the Ehcache when the VM restarts, false by default.
Diskexpirythreadintervalseconds-Disk cache cleanup thread run interval, default is 120 seconds. Each 120s, the corresponding thread will do a ehcache of data in the cleanup work
Memorystoreevictionpolicy-Removes the policy of the element in the cache when the memory cache reaches the maximum and a new element joins. Default is LRU (least recently used), optional lfu (most infrequently used) and FIFO (first-in first Out)
Second-level application scenario
For access to many query requests and the user's real-time requirements for query results are not high, at this time can use MyBatis two cache technology to reduce database access, improve access speed, business scenarios such as: time-consuming statistical analysis of SQL, telephone billing query SQL.
The implementation method is as follows: By setting the refresh interval time, automatically clears the cache by the MyBatis every time, according to the data change frequency sets the cache refresh interval flushinterval, for instance set to 30 minutes, 60 minutes, 24 hours, according to the requirement.
Second-level cache limitations
MyBatis Level Two cache is not good for fine-grained data-level caching, such as the following requirements: To cache merchandise information, because of the large number of commodity information query access, but require users to be able to query the latest commodity information every time, At this point, if you use the MyBatis level two cache, you will not be able to refresh the information on the cached information of the product when a product changes, as the level two cache area of the mybaits is divided into mapper units, when a change in merchandise information will empty all the cached data of the product information. Resolving such problems requires a targeted caching of data at the business level based on requirements.