MyBatis: implement paging of

Log factory

Question: When we tested SQL, SQL output in the console if you could, then, is not to be able to have faster troubleshooting efficiency?

If a database-related operational problems, we can quickly troubleshoot problems based on SQL statement output.

For the past development process, we often use to debug mode to adjust the tracking our code execution. But now Mybatis is based on the interface, the profile of the source code execution. Therefore, we must choose the log as a tool to develop us, utility regulation.

Mybatis built-in log facility provides log function, specific logging implementation are the following tools:

  • SLF4J
  • Apache Commons Logging
  • Log4j 2
  • Laog4j
  • JDK logging

The specific choice of which is determined by the log implementation tool built MyBatis log factory. It will use the first found (Find the order listed above). If one is not found, the log function is disabled.

Standard logging implementation

MyBatis specify which log records should be used to achieve. If this setting does not exist, it will automatically discover logging implementation.

<settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/> </settings>

Test, you can see a large number of console output! We can be judged by the output of the program in the end, where is the Bug

Laog4j

Summary:

  • Apache Log4j is an open source project
  • By using Log4j, we can control the destination log information delivery: the console, text, GUI components ....
  • We can also control the output format of each log;
  • Each level is defined by a log of information, we can more carefully control the build process logs. The most interesting is that these can be flexibly configured via a configuration file, without modifying the application code.

Steps for usage:

  1. Introducing package log4j

    <dependency>
        <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
  2. Write configuration file

    #将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
    log4j.rootLogger=DEBUG,console,file
    
    #控制台输出的相关设置
    log4j.appender.console = org.apache.log4j.ConsoleAppender log4j.appender.console.Target = System.out log4j.appender.console.Threshold=DEBUG log4j.appender.console.layout = org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=[%c]-%m%n  #文件输出的相关设置 log4j.appender.file = org.apache.log4j.RollingFileAppender log4j.appender.file.File=./log/kuang.log log4j.appender.file.MaxFileSize=10mb log4j.appender.file.Threshold=DEBUG log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n  #日志输出级别 log4j.logger.org.mybatis=DEBUG log4j.logger.java.sql=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.ResultSet=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
  3. Set the log setting to achieve

    <settings>
        <setting name="logImpl" value="LOG4J"/> </settings>
  4. Use Log4j output in the program!

    //注意导包:org.apache.log4j.Logger
    static Logger logger = Logger.getLogger(MyTest.class);
    
    @Test
    public void selectUser() { logger.info("info:进入selectUser方法"); logger.debug("debug:进入selectUser方法"); logger.error("error: 进入selectUser方法"); SqlSession session = MybatisUtils.getSession(); UserMapper mapper = session.getMapper(UserMapper.class); List<User> users = mapper.selectUser(); for (User user: users){ System.out.println(user); } session.close(); }
  5. Test to see if the console output!

    • Use Log4j log output
    • See also generates a log file of the need to modify the file [log level]

limit implement paging

Question: Why do I need pagination?

When learning persistence framework mybatis etc., often the data CRUD operations, most use is the database query, if the query large amounts of data, we often use paging query, that is, each time a small processing part of the data, the database so that the pressure in the controllable range.

Use Limit implement paging

#语法
SELECT * FROM table LIMIT stratIndex,pageSize SELECT * FROM table LIMIT 5,10; // 检索记录行 6-15 #为了检索从某一个偏移量到记录集的结束所有的记录行,可以指定第二个参数为 -1: SELECT * FROM table LIMIT 95,-1; // 检索记录行 96-last. #如果只给定一个参数,它表示返回最大的记录行数目: SELECT * FROM table LIMIT 5; //检索前 5 个记录行 #换句话说,LIMIT n 等价于 LIMIT 0,n。 

step:

  1. Modify Mapper file

    <select id="selectUser" parameterType="map" resultType="user"> select * from user limit #{startIndex},#{pageSize} </select>
  2. Mapper interface parameters for the map

    //选择全部用户实现分页
    List<User> selectUser(Map<String,Integer> map);
  3. Incoming parametric tests in the test class

    • Inference: = start position (current page - 1) * page size
    //分页查询 , 两个参数startIndex , pageSize
    @Test
    public void testSelectUser() { SqlSession session = MybatisUtils.getSession(); UserMapper mapper = session.getMapper(UserMapper.class); int currentPage = 1; //第几页 int pageSize = 2; //每页显示几个 Map<String,Integer> map = new HashMap<String,Integer>(); map.put("startIndex",(currentPage-1)*pageSize); map.put("pageSize",pageSize); List<User> users = mapper.selectUser(map); for (User user: users){ System.out.println(user); } session.close(); }

RowBounds page

We implement paging in addition to using the Limit SQL level, it can also be used RowBounds implemented in Java code level paging, of course, as understood in this way can be. We look at how to achieve it!

step:

  1. mapper Interface

    //选择全部用户RowBounds实现分页
    List<User> getUserByRowBounds();
  2. mapper file

    <select id="getUserByRowBounds" resultType="user"> select * from user </select>
  3. Test class
    here, we need to use RowBounds class

    @Test
    public void testUserByRowBounds() { SqlSession session = MybatisUtils.getSession(); int currentPage = 2; //第几页 int pageSize = 2; //每页显示几个 RowBounds rowBounds = new RowBounds((currentPage-1)*pageSize,pageSize); //通过session.**方法进行传递rowBounds,[此种方式现在已经不推荐使用了] List<User> users = session.selectList("com.kuang.mapper.UserMapper.getUserByRowBounds", null, rowBounds); for (User user: users){ System.out.println(user); } session.close(); }

PageHelper

1567048504996.png

Can understand, you can try to use their own

The official document: https://pagehelper.github.io/

Guess you like

Origin www.cnblogs.com/wpy188/p/12375439.html