JAVAEE look at the framework 09-Mybatis dynamic sql mapping, core configuration file in-depth, pageHelper use

1. Mybatis Dao layer implementation

1.1 Traditional development methods

1.1.1 Writing UserDao interface
public interface UserDao {
    List<User> findAll() throws IOException;
}
1.1.2. Writing 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 Testing traditional methods
@Test
public void testTraditionDao() throws IOException {
    UserDao userDao = new UserDaoImpl();
    List<User> all = userDao.findAll();
    System.out.println(all);
}

1.2 Agent development method

1.2.1 Introduction to agent development

Using Mybatis' agent development method to realize the development of the DAO layer, this method is the mainstream that we enter the enterprise later.

The Mapper interface development method only requires the programmer to write the Mapper interface (equivalent to the Dao interface). The Mybatis framework creates a dynamic proxy object of the interface according to the interface definition. The method body of the proxy object is the same as the Dao interface implementation class method 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 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 of each sql defined in mapper.xml

1.2.2 Writing UserMapper interface

Insert picture description here

1.2.3 Test proxy method
@Test
public void testProxyDao() throws IOException {
    InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //获得MyBatis框架生成的UserMapper接口的实现类
  UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    User user = userMapper.findById(1);
    System.out.println(user);
    sqlSession.close();
}

1.3 Summary of knowledge

Two ways to realize the Dao layer of MyBatis:

Implementing Dao manually: traditional development methods

Acting way to realize Dao:

 **UserMapper userMapper = sqlSession.getMapper(UserMapper.class);**

2. MyBatis mapping file in-depth

2.1 Dynamic SQL statement

2.1.1 Overview of Dynamic SQL Statements

In 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 cannot meet the requirements in the previous study.

Refer to the official documentation, described as follows:
Insert picture description here

2.1.2 Dynamic SQL < if>

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 based on the id. If the username is different, add the username as a condition. This situation is often encountered in our multi-condition combination query.

<select id="findByCondition" parameterType="user" resultType="user">
    select * from User
    <where>
        <if test="id!=0">
            and id=#{id}
        </if>
        <if test="username!=null">
            and username=#{username}
        </if>
    </where>
</select>

When the query condition id and username both exist, the SQL statement printed by the console is as follows:

     … … …
     //获得MyBatis框架生成的UserMapper接口的实现类
  UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    User condition = new User();
    condition.setId(1);
    condition.setUsername("lucy");
    User user = userMapper.findByCondition(condition);
    … … …

Insert picture description here

When only the id of the query condition exists, the SQL statement printed by the console is as follows:

 … … …
 //获得MyBatis框架生成的UserMapper接口的实现类
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User condition = new User();
condition.setId(1);
User user = userMapper.findByCondition(condition);
… … …

Insert picture description here

2.1.3 Dynamic SQL < foreach>

Execute the splicing operation of SQL in a loop, 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=",">
           #{id}
       </foreach>
   </where>
</select>

The test code snippet is as follows:

//获得MyBatis框架生成的UserMapper接口的实现类
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int[] ids = new int[]{2,5};
List<User> userList = userMapper.findByIds(ids);
System.out.println(userList);

Insert picture description here

The meaning of the attributes of the foreach tag is as follows:

The label is used to traverse the collection, its attributes:

• collection: represents the collection elements to be traversed, pay attention not to write # {} when writing

• open: represents the beginning of the statement

• close: represents the end part

• item: represents the variable name generated by traversing each element of the collection

• sperator: on behalf of the separator

2.2 SQL fragment extraction

Repeated sql can be extracted from Sql, use include reference when using, and finally achieve the purpose of sql reuse

<!--抽取sql片段简化编写-->
<sql id="selectUser">select * from User</sql>
<select id="findById" parameterType="int" resultType="user">
    <include refid="selectUser"></include> where id=#{id}
</select>
<select id="findByIds" parameterType="list" resultType="user">
    <include refid="selectUser"></include>
    <where>
        <foreach collection="array" open="id in(" close=")" item="id" separator=",">
            #{id}
        </foreach>
    </where>
</select>

2.3 Summary of knowledge

MyBatis mapping file configuration:

<select>:查询

<insert>:插入

<update>:修改

<delete>:删除

<where>:where条件

<if>:if判断

<foreach>:循环

<sql>:sql片段抽取

3. MyBatis core configuration file in-depth

3.1typeHandlers tags

Whether MyBatis sets a parameter in a prepared statement (PreparedStatement) or extracts a value from the result set, the obtained value will be converted into a Java type in a suitable manner by a type processor. The following table describes some default type processors (interception part).
Insert picture description here

You can rewrite the type processor or create your own type processor to handle unsupported or non-standard types. The specific approach is: implement the org.apache.ibatis.type.TypeHandler interface, or inherit a convenient class org.apache.ibatis.type.BaseTypeHandler, and then you can selectively map it to a JDBC type. For example, a requirement: a Date data type in Java. I want to save it as a millisecond number from 1970 to the present when it is stored in the database. When it is taken out, it is converted into java Date, which is the java Date and the database varchar millisecond value. Conversion.

Development steps:

① Define the conversion class inherited class BaseTypeHandler

② Cover 4 unimplemented methods, of which setNonNullParameter is the callback method for the java program to set the data to the database, getNullableResult is the method of converting the mysql string type to java Type type when querying

③ Register in the MyBatis core configuration file

Test for correct conversion

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);
    }
}
<!--注册类型自定义转换器-->
<typeHandlers>
    <typeHandler handler="com.ittest.typeHandlers.MyDateTypeHandler"></typeHandler>
</typeHandlers>

Test add operation:

user.setBirthday(new Date());
userMapper.add2(user);

Database data:

Insert picture description here

Test query operation:

Insert picture description here

3.2 plugins tags

MyBatis can use third-party plug-ins to expand the function, the paging assistant PageHelper is to encapsulate the complex operations of paging, and you can obtain the relevant data of paging in a simple way

Development steps:

① Import the coordinates of the general PageHelper

② Configure PageHelper plug-in in the core configuration file of mybatis

③Test paging data acquisition

① Import general PageHelper coordinates

Insert picture description here

② Configure PageHelper plug-in in the core configuration file of mybatis

Insert picture description here
Details
Insert picture description here

③ Test paging code implementation
@Test
public void testPageHelper(){
    //设置分页参数
    PageHelper.startPage(1,2);

    List<User> select = userMapper2.select(null);
    for(User user : select){
        System.out.println(user);
    }
}

Get other parameters related to paging

//其他分页的数据
PageInfo<User> pageInfo = new PageInfo<User>(select);
System.out.println("总条数:"+pageInfo.getTotal());
System.out.println("总页数:"+pageInfo.getPages());
System.out.println("当前页:"+pageInfo.getPageNum());
System.out.println("每页显示长度:"+pageInfo.getPageSize());
System.out.println("是否第一页:"+pageInfo.isIsFirstPage());
System.out.println("是否最后一页:"+pageInfo.isIsLastPage());

3.3 Summary of knowledge

Common tags of MyBatis core configuration file:

1. Properties tag: This tag can load external properties files

2. typeAliases tag: set type alias

3. Environments label: data source environment configuration label

4. typeHandlers tag: configure custom type processors

5. plugins tag: configure MyBatis plugin

"
78 original articles published · Liked 30 · Visits 3634

Guess you like

Origin blog.csdn.net/ZMW_IOS/article/details/105239881