mybatis Java framework (three) - mybatis achieve paging, project optimization: automatic submission to realize the transaction, using annotations development

Mybatis achieve paging

mysql pagination statement

select * from user limit #{startIndex},#{pageSize};
# startIndex : 起始位置 ,默认是0开始
# pageSize :页面大小
# 如何计算出当前页面
currentPage = (currentPage-1)* pageSize 

Use the limit to achieve pagination [master]

1. Use a limit to achieve pagination [master]
write UserDao:

//查询全部用户实现分页
List<User> selectUserByLimit(Map<String,Integer> map);

2. The method of preparation of the corresponding mapper mapping file
Parameters We can use the map package, convenient parameter passed]

<select id="selectUserByLimit" parameterType="Map" resultType="User">
    select * from mybatis.user limit #{startIndex},#{pageSize}
</select>

3. Test
[Analog paged data: currentPage, pageSize]

@Test
public void selectUserByLimit(){

    //创建sqlSession
    SqlSessionFactory sqlSessionFactory = MyBatisUtils.getSqlSessionFactory();
    SqlSession sqlSession = sqlSessionFactory.openSession();

    //准备数据
    int currentPage = 2;//当前是第几页
    int pageSize = 2; //页面大小

    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("startIndex",(currentPage-1)*pageSize);
    map.put("pageSize",pageSize);

    //测试
    UserDao mapper = sqlSession.getMapper(UserDao.class);
    List<User> users = mapper.selectUserByLimit(map);

    for (User user : users) {
        System.out.println(user);
    }

    sqlSession.close();//关闭连接

}

Case realization:
Project Structure:
Here Insert Picture Description
UserDao layer write:

package com.kuang.dao;

import com.kuang.pojo.User;

import java.util.List;
import java.util.Map;

public interface UserDao {

    //查询全部用户实现分页
    List<User> selectUserByLimit(Map<String,Integer> map);

}


Write the corresponding userMapper.xml profile:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.kuang.dao.UserDao">


    <select id="selectUserByLimit" parameterType="Map" resultType="User">
        select * from mybatis.user limit #{startIndex},#{pageSize}
    </select>

    <select id="selectUserByRowBounds" resultType="User">
        select * from mybatis.user
    </select>

</mapper>

Test results:
Here Insert Picture Description
total points of the two second page currently displayed user;

Use RowBounds implement paging (understand)

1. Write Interface

//查询全部用户实现分页使用RowBounds
List<User> selectUserByRowBounds();

2. Write Mapper mapping file

<select id="selectUserByRowBounds" resultType="User">
    select * from mybatis.user
</select>

3. Write test code

@Test
public void selectUserByRowBounds(){
    //创建sqlSession
    SqlSessionFactory sqlSessionFactory = MyBatisUtils.getSqlSessionFactory();
    SqlSession sqlSession = sqlSessionFactory.openSession();

    int currentPage = 2; //当前页
    int pageSize = 2; //页面大小

    RowBounds rowBounds = new RowBounds((currentPage - 1) * pageSize, pageSize);

    //注意点;使用RowBounds就不能使用getMapper了
    //selectList: 接收一个List
    //selectMap: 接收一个Map
    //selectOne : 接收只有一个对象的时候

    List<User> users = sqlSession.selectList("com.kuang.dao.UserDao.selectUserByRowBounds", null, rowBounds);

    for (User user : users) {
        System.out.println(user);
    }


}

Test Results:
Here Insert Picture Description
A total of two output displayed as the first page of the user;

limit and rowBounds difference

  • rowBounds essentially encapsulates the limit
  • limit is to implement paging in the SQL level
  • rowBounds implement paging code level

Optimization Project (transaction automatically submitted)

Thoughts? Our previous code, but also in optimizing it?

Logs, tools, configuration files, aliases ... affairs

mybaits developers also thought to have a constructor, the transaction can be achieved automatically submitted.

openSession (true); // openSession constructor if the argument is true, the transaction is automatically committed. We do not always commit;


Transaction Optimization: Auto commit the transaction

//获得一个带事务自动提交功能的SqlSession公共的方法
public static SqlSession getSqlSession(){
    //自动提交事务
    return sqlSessionFactory.openSession(true);
}

Alias ​​Optimization: pojo pack that automatically set based alias

<!--配置别名-->
<typeAliases>
    <!--<typeAlias type="com.kuang.pojo.User" alias="User"/>-->
    <package name="com.kuang.pojo"/>
</typeAliases>

mapper mapping file path modification

<mappers>
    <!--class对应的是一个接口类-->
    <!--resource对应的是一个接口类的映射文件-->
    <mapper class="com.kuang.dao.UserDao"/>
</mappers>

Project realization

1. Project structure:
Here Insert Picture Description
2.myBatisUitils documents prepared

package com.kuang.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;


//mybatis的工具类,重复的代码的提纯
public class MyBatisUtils {

    //类变量不需要设置默认值;
    private static SqlSessionFactory sqlSessionFactory;

    static {

        //在maven中,所有的资源文件一般都放在resources目录下,我们可以直接拿到。
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //设置SqlSessionFactory公共的方法
    public static SqlSessionFactory getSqlSessionFactory(){
        return sqlSessionFactory;
    }

    //获得一个带事务自动提交功能的SqlSession公共的方法
    public static SqlSession getSqlSession(){
        //自动提交事务
        return sqlSessionFactory.openSession(true);
    }


}

Write 3.userDaoTest file:

package com.kuang.dao;

import com.kuang.pojo.User;
import com.kuang.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserDaoTest {

    @Test
    public void getUserList(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();//带自动提交事务

        UserDao mapper = sqlSession.getMapper(UserDao.class);

        List<User> userList = mapper.getUserList();

        for (User user : userList) {
            System.out.println(user);
        }

        sqlSession.close();//关闭sqlSession;

    }

    @Test
    public void getUserById(){

        SqlSession sqlSession = MyBatisUtils.getSqlSession();//带自动提交事务

        UserDao mapper = sqlSession.getMapper(UserDao.class);

        User user = mapper.getUserById(1);

        System.out.println(user);

        sqlSession.close();//关闭sqlSession;

    }

    @Test
    public void addUser(){

        SqlSession sqlSession = MyBatisUtils.getSqlSession();//带自动提交事务
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        User user = new User(5, "阿猫", "like-dog");
        int i = mapper.addUser(user);
        System.out.println(i);

        sqlSession.close();//关闭sqlSession;

    }

    @Test
    public void updateUser(){

        SqlSession sqlSession = MyBatisUtils.getSqlSession();//带自动提交事务
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        User user = new User(5, "阿狗", "like-cat");
        int i = mapper.updateUser(user);
        System.out.println(i);

        sqlSession.close();//关闭sqlSession;

    }

    @Test
    public void deleteUser(){

        SqlSession sqlSession = MyBatisUtils.getSqlSession();//带自动提交事务
        UserDao mapper = sqlSession.getMapper(UserDao.class);

        int i = mapper.deleteUser(5);
        System.out.println(i);

        sqlSession.close();//关闭sqlSession;

    }

}

Oriented programming interface

The reason put forward: decoupling , easy to expand and improve the reusability of code, do not control the upper lower realized, spent only call the corresponding interfaces can be. Normative good.

Process-oriented programming: With the system more and more, we can not use process-oriented thinking meet. The face of the object.

Object-Oriented Programming: high coupling all systems, all functions are composed of many different objects to accomplish. As the system is growing.

Interface & abstract class

Oriented programming interface: developers operating constraints, and to facilitate the expansion and planning.

Deeper separation: the definition and implementation of a separation;

The interface may reflect a low level of personnel development and understanding of the system architecture;

Use annotations Development

Early, mybatis are carried out using xml configuration until the notes, the notes may replace some xml configuration.

Do not even the xml configuration!

CRUD comments:

  • @insert()
  • @delete()
  • @update()
  • @select()

UserDao.java

package com.kuang.dao;

import com.kuang.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface UserDao {

    //查询全部用户
    @Select("select * from user")
    List<User> getUserList();

    //通过ID查询用户
    @Select("select * from user where id = #{id}")
    User getUserById(@Param("id") int id);

    //添加用户
    @Insert("insert into user(id,name,pwd) values (#{id},#{name},#{pwd})")
    int addUser(User user);

    //修改用户信息
    @Update("update user set name = #{name}, pwd = #{pwd} where id = #{id}")
    int updateUser(User user);

    //删除用户
    @Delete("delete from user where id =#{uid}")
    int deleteUser(@Param("uid") int id);

}

mybatis core file
does not use Notes before:
Here Insert Picture Description
using annotations:
Here Insert Picture Description
mybatis-config.xml file:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <!--配置文件修改-->
    <properties resource="database.properties"/>

    <!--Mybatis设置-->
    <settings>
        <!--默认日志实现-->
        <!--<setting name="logImpl" value="STDOUT_LOGGING"/>-->

        <!--Log4j实现-->
        <setting name="logImpl" value="LOG4J"/>
    </settings>

    <!--配置别名-->
    <typeAliases>
        <!--<typeAlias type="com.kuang.pojo.User" alias="User"/>-->
        <package name="com.kuang.pojo"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!--class对应的是一个接口类-->
        <!--resource对应的是一个接口类的映射文件-->
        <mapper class="com.kuang.dao.UserDao"/>
    </mappers>

</configuration>

Test category

package com.kuang.dao;

import com.kuang.pojo.User;
import com.kuang.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import sun.rmi.server.UnicastServerRef;

import java.util.List;


public class UserDaoTest {

    @Test
    public void getUserList(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();//带自动提交事务

        UserDao mapper = sqlSession.getMapper(UserDao.class);

        List<User> userList = mapper.getUserList();

        for (User user : userList) {
            System.out.println(user);
        }

        sqlSession.close();//关闭sqlSession;

    }

    @Test
    public void getUserById(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();//带自动提交事务

        UserDao mapper = sqlSession.getMapper(UserDao.class);

        User user = mapper.getUserById(1);

        System.out.println(user);

        sqlSession.close();//关闭sqlSession;

    }
    

    @Test
    public void addUser(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();//带自动提交事务
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        User user = new User(5, "阿猫", "like-dog");
        int i = mapper.addUser(user);
        System.out.println(i);

        sqlSession.close();//关闭sqlSession;

    }

    @Test
    public void updateUser(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();//带自动提交事务
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        User user = new User(5, "阿狗", "like-cat");
        int i = mapper.updateUser(user);
        System.out.println(i);

        sqlSession.close();//关闭sqlSession;

    }

    @Test
    public void deleteUser(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();//带自动提交事务
        UserDao mapper = sqlSession.getMapper(UserDao.class);

        int i = mapper.deleteUser(5);
        System.out.println(i);

        sqlSession.close();//关闭sqlSession;

    }
}

Precautions

  1. Open transaction automatically submitted
  2. @param parameters are written on as much as possible, if there are multiple parameters, you must fill out.
Published 84 original articles · won praise 15 · views 10000 +

Guess you like

Origin blog.csdn.net/yalu_123456/article/details/98312417