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/02 Report--
Java Mybatis framework Dao layer implementation and mapping files and core configuration file example analysis, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can get something.
The Dao layer of Mybatis implements the traditional development method
1. Write UserDao interface
Public interface UserMapper {public List findAll () throws IOException;}
2. Write UserDaoImpl implementation
3. Test the traditional way
Agent development mode
Introduction of agent development method
The agent development method of Mybatis is used to realize the development of DAO layer, which is the mainstream for us to enter the enterprise.
The Mapper interface development method only needs the programmer to write the Mapper interface (equivalent to the Dao interface), and the Mybatis framework creates the dynamic proxy object of the interface according to the interface definition, and the method body of the proxy object is the same as the above Dao interface implementation class method.
Mapper interface development needs to follow the following specifications:
The namespace in the ① Mapper.xml file has the same fully qualified name as the mapper interface
The ② Mapper interface method name is the same as the id for each statement defined in Mapper.xml
The input parameter type of the ③ Mapper interface method is the same as the parameterType type of each sql defined in mapper.xml. 4. The output parameter type of the ④ Mapper interface method is the same as the resultType type of each sql defined in mapper.xml.
With
1. Write UserMapper interface
2. Test agent mode
MyBatis mapping file goes deep into dynamic sql statements
Dynamic sql statement description [official documentation]
Dynamic SQL
We use different SQL statements to query according to the different values of the entity class. For example, if the id is not empty, you can query according to id, and add the user name as a condition if the username is different. This situation is often encountered in our multi-conditional combination queries.
Select * from user and id=# {id} and username=# {username} and password=# {password}
When the query conditions id and username exist, the test code is as follows
Dynamic SQL
The loop performs the stitching operation of sql, for example: SELECT * FROM USER WHERE id IN (1 ~ 2 ~ 5).
# {id}
The test code is as follows
The attribute meaning of the foreach tag is as follows:
The tag is used to traverse the collection, and its properties are:
① collection: represents the collection element to be traversed. Be careful not to write # {} when writing
② open: represents the beginning of the statement
③ close: represents the closing section
④ item: represents the name of the generated variable for each element of the traversal collection
⑤ sperator: represents the delimiter
SQL fragment extraction
The duplicate sql can be extracted from Sql and can be referenced by include when using it, so as to achieve the purpose of sql reuse.
Summary
MyBatis mapping file configuration:
Query
: insert
: modify
: deletin
Where condition
If judgment
: cycle
Sql fragment extraction
The Mybatis core profile goes deep into the typeHandlers tag
Whether MyBatis sets a parameter in a preprocessing statement (PreparedStatement) or fetches a value from the result set, the type handler converts the acquired value to the Java type in an appropriate manner. The following table describes some of the default type handlers (intercept section).
You can override type handlers or create your own type handlers to handle unsupported or non-standard types. To do this: implement the org.apache.ibatis.type.TypeHandler interface, or inherit a convenient class, org.apache.ibatis.type.BaseTypeHandler, and optionally map it to a JDBC type. For example, the requirement: a Date data type in Java, which I want to save to a database in milliseconds from 1970 to the present, and when taken out, it is converted to the Date of java, that is, the conversion between the Date of java and the Varchar millisecond value of the database.
Development steps:
① defines the transformation class inheritance class BaseTypeHandler
② covers four unimplemented methods, in which setNonNullarameter sets the callback method of data to the database for the java program, and getNullableResult is the method for converting the string type of mysql to the Type type of java when querying.
③ registers in the MyBatis core configuration file
④ tests whether the conversion is correct
Public class DateTypeHandler extends BaseTypeHandler {/ / convert the java type to the type required by the database public void setNonNullParameter (PreparedStatement preparedStatement, int I, Date date, JdbcType jdbcType) throws SQLException {long time = date.getTime (); preparedStatement.setLong (iQuery time) } / / convert the type in the database to java type / / the field name to be converted by the String parameter / / the result set queried by ResultSet public Date getNullableResult (ResultSet resultSet, String s) throws SQLException {/ / get the data needed in the result set (long) convert to Date type return long aLong = resultSet.getLong (s); Date date = new Date (aLong); return date } / / convert types in the database to java types public Date getNullableResult (ResultSet resultSet, int I) throws SQLException {long aLong = resultSet.getLong (I); Date date = new Date (aLong); return date;} / / convert types in the database to java types public Date getNullableResult (CallableStatement callableStatement, int I) throws SQLException {long aLong = callableStatement.getLong (I) Date date = new Date (aLong); return date;}}
Test add operation
Database data:
Plugins tag
MyBatis can use third-party plug-ins to expand the function. The paging assistant PageHelper encapsulates the complex operation of paging and uses a simple way to obtain the relevant data of paging.
Development steps:
① imports coordinates of generic PageHelper
② configures the PageHelper plug-in in the mybatis core configuration file
③ test paging data acquisition
① imports coordinates of generic PageHelper
Com.github.pagehelper pagehelper 3.7.5 com.github.jsqlparser jsqlparser 0.9.1
② configures the PageHelper plug-in in the mybatis core configuration file
③ test paging data acquisition
Get other parameters related to paging
/ / get the parameters related to paging PageInfo pageInfo = new PageInfo (userList); System.out.println ("current page:" + pageInfo.getPageNum ()); System.out.println ("number of entries per page:" + pageInfo.getPageSize ()); System.out.println ("total number of pages:" + pageInfo.getTotal ()); System.out.println ("total pages:" + pageInfo.getPages ()) System.out.println ("previous page:" + pageInfo.getPrePage ()); System.out.println ("next page:" + pageInfo.getNextPage ()); System.out.println ("whether it is the first:" + pageInfo.isIsFirstPage ()); System.out.println ("is it the last:" + pageInfo.isIsLastPage ()); summary
Common tags for MyBatis core configuration files:
1. Properties tag: this tag can load external properties files
2. TypeAliases tag: set type alias
3. Environments tag: data source environment configuration label
4. TypeHandlers tag: configure custom type handlers
5. Plugins tag: configure the plug-in for MyBatis
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
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.