1. Dao layer implementation of mybatis
1.1 traditional development methods 1.1.1 write UserDao interfacepublic interface UserDao { List<User> findAll() throws IOException; }1.1.2. Write UserDaoImpl implementation
public class UserDaoImpl implements UserDao { public List<User> findAll() throws IOException { InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession sqlSession = sqlSessionFactory.openSession(); List<User> userList = sqlSession.selectList("userMapper.findAll"); sqlSession.close(); return userList; } }1.1.3 traditional test methods
@Test public void testTraditionDao() throws IOException { UserDao userDao = new UserDaoImpl(); List<User> all = userDao.findAll(); System.out.println(all); }1.2 agent development mode 1.2.1 introduction to agent development mode
The agent development method of Mybatis is adopted to realize the development of DAO layer, which is the mainstream of entering the enterprise later.
Mapper interface development method only requires programmers to write mapper interface (equivalent to Dao interface). Mybatis framework creates the dynamic proxy object of the interface according to the interface definition. The method body of the proxy object is the same as that of the Dao interface above.
Mapper interface development needs to follow the following specifications:
1) The namespace in the mapper.xml file is the same as the fully qualified name of the mapper interface
2) The mapper interface method name is the same as the id of each statement defined in Mapper.xml
3) The input parameter type of mapper interface method is the same as the parameterType of each sql defined in mapper.xml
4) The output parameter type of mapper interface method is the same as the resultType of each sql defined in mapper.xml
1.2.2 writing UserMapper interface 1.2.3 test agent mode@Test public void testProxyDao() throws IOException { InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession sqlSession = sqlSessionFactory.openSession(); //Get the implementation class of UserMapper interface generated by MyBatis framework UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.findById(1); System.out.println(user); sqlSession.close(); }1.3 knowledge summary
There are two ways to implement the Dao layer of MyBatis:
Manual implementation of Dao: traditional development method
Dao is implemented by proxy:
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
2.MyBatis mapping file depth
2.1 dynamic sql statements 2.1.1 overview of dynamic sql statementsIn the mapping file of Mybatis, our SQL is relatively simple. Sometimes when the business logic is complex, our SQL changes dynamically. At this time, our SQL can not meet the requirements in the previous study.
Refer to the official documents described below:
2.1.2 dynamic SQL < if >We use different SQL statements to query according to different values of entity classes. For example, if the id is not empty, you can query according to the id. if the username is not empty, you need to add the user name as a condition. This situation is often encountered in our multi condition combined query.
<select id="findByCondition" parameterType="user" resultType="user"> select * from User <where> <if test="id!=0"> and id=# </if> <if test="username!=null"> and username=# </if> </where> </select>
When both query condition id and username exist, the sql statement printed on the console is as follows:
//Get the implementation class of UserMapper interface generated by MyBatis framework UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User condition = new User(); condition.setId(1); condition.setUsername("lucy"); User user = userMapper.findByCondition(condition);
When only id exists in the query condition, the sql statement printed on the console is as follows:
... ... ... //Get the implementation class of UserMapper interface generated by MyBatis framework UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User condition = new User(); condition.setId(1); User user = userMapper.findByCondition(condition); ... ... ...2.1.3 < foreach > of dynamic SQL
Perform sql splicing operations circularly, for example: SELECT * FROM USER WHERE id IN (1,2,5).
<select id="findByIds" parameterType="list" resultType="user"> select * from User <where> <foreach collection="array" open="id in(" close=")" item="id" separator=","> # </foreach> </where> </select>
The test code fragment is as follows:
... ... ... //Get the implementation class of UserMapper interface generated by MyBatis framework UserMapper userMapper = sqlSession.getMapper(UserMapper.class); int[] ids = new int[]; List<User> userList = userMapper.findByIds(ids); System.out.println(userList); ... ... ...
The attribute meaning of foreach tag is as follows:
Tag is used to traverse the collection. Its properties are:
• collection: represents the collection elements to be traversed. Be careful not to write #{}
• open: represents the beginning of a statement
• close: represents the end part
• item: represents the variable name generated by traversing each element of the collection
• sperator: represents the separator
2.2 SQL fragment extractionDuplicate sql can be extracted from sql and referenced with include when used, so as to achieve the purpose of sql reuse
<!--extract sql Fragment simplification--> <sql id="selectUser" select * from User</sql> <select id="findById" parameterType="int" resultType="user"> <include refid="selectUser"></include> where id=# </select> <select id="findByIds" parameterType="list" resultType="user"> <include refid="selectUser"></include> <where> <foreach collection="array" open="id in(" close=")" item="id" separator=","> # </foreach> </where> </select>
3. MyBatis core configuration file
3.1 typehandlers labelWhether MyBatis sets a parameter in the PreparedStatement or takes a value from the result set, it will use the type processor to convert the obtained value into Java type in an appropriate way. The following table describes some of the default processor types (interceptions).
You can override the type processor or create your own type processor to handle unsupported or nonstandard types. The specific approach is to implement the org.apache.ibatis.type.TypeHandler interface, or inherit a convenient class org.apache.ibatis.type.BaseTypeHandler, and then selectively map it to a JDBC type. For example, requirements: for a Date data type in Java, when I want to save it to the database, I want to save it as a millisecond since 1970, and when I take it out, it will be converted into a Java Date, that is, the conversion between the Java Date and the varchar millisecond value of the database.
Development steps:
① Defines the transformation class and inherits the class BaseTypeHandler
② It covers four unimplemented methods, among which setNonNullParameter is the callback method for java program to set data to the database, and getNullableResult is the method for converting mysql string Type into java Type during query
③ Register in the MyBatis core configuration file
Test whether the conversion is correct
public class MyDateTypeHandler extends BaseTypeHandler<Date> { public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType type) { preparedStatement.setString(i,date.getTime()+""); } public Date getNullableResult(ResultSet resultSet, String s) throws SQLException { return new Date(resultSet.getLong(s)); } public Date getNullableResult(ResultSet resultSet, int i) throws SQLException { return new Date(resultSet.getLong(i)); } public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException { return callableStatement.getDate(i); } }
<!--Register type custom converter--> <typeHandlers> <typeHandler handler="com.itheima.typeHandlers.MyDateTypeHandler"></typeHandler> </typeHandlers>
Test add operation:
user.setBirthday(new Date()); userMapper.add2(user);
Database data:
Test query operation:
3.2 plugins tabMyBatis can use third-party plug-ins to extend its functions. The paging assistant PageHelper encapsulates the complex operations of paging, and can obtain paging related data in a simple way
Development steps:
① Import the coordinates of the generic PageHelper
② Configure the PageHelper plug-in in the mybatis core configuration file
③ Test paging data acquisition
① Import common PageHelper coordinates<!-- Paging assistant --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>3.7.5</version> </dependency> <dependency> <groupId>com.github.jsqlparser</groupId> <artifactId>jsqlparser</artifactId> <version>0.9.1</version> </dependency>② Configure the PageHelper plug-in in the mybatis core configuration file
<!-- Note: the plug-in of paging assistant is configured in the general library mapper before --> <plugin interceptor="com.github.pagehelper.PageHelper"> <!-- Designated dialect --> <property name="dialect" value="mysql"/> </plugin>③ Test paging code implementation
@Test public void testPageHelper(){ //Set paging parameters PageHelper.startPage(1,2); List<User> select = userMapper2.select(null); for(User user : select){ System.out.println(user); } }
Get other parameters related to paging
//Other paged data PageInfo<User> pageInfo = new PageInfo<User>(select); System.out.println("Total number of pieces:"+pageInfo.getTotal()); System.out.println("Total pages:"+pageInfo.getPages()); System.out.println("Current page:"+pageInfo.getPageNum()); System.out.println("Display length per page:"+pageInfo.getPageSize()); System.out.println("First page:"+pageInfo.isIsFirstPage()); System.out.println("Last page:"+pageInfo.isIsLastPage());3.3 knowledge summary
MyBatis core profile common Tags:
1. Properties tag: this tag can load external properties files
2. typeAliases label: set type aliases
3. environments tab: data source environment configuration tab
4. typeHandlers tab: configure custom type processors
5. plugins tag: configure MyBatis plug-in