• 周六. 10 月 5th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Mybatis learning (3) — implementation of Java log (log4j) / pagination implementation / optimized u

King Wang

1 月 3, 2022

Mybatis Study ( 3、 … and )—Java journal (log4j) The implementation of the / Paging implementation /Mybatis Optimized use of ( Business / Alias / annotation )

01 Java Log implementation

Mybatis The built-in log factory of provides the log function , The built-in log factory gives the log to one of the following tools as an agent :

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

Preparation steps :

  1. Maven Warehouse downloading log4j Dependence
<!--log4j rely on -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
  1. stay resources Store in the directory log4j.properties file
### Log4j To configure ###
### And Spring The combination needs to be in web.xml The location of this file is specified in , And add a monitor ###
# Definition log4j Output level and output destination ( A destination can have a custom name , Corresponding to the following )
#[ level ] , appenderName1 , appenderName2
log4j.rootLogger=DEBUG,console,file
#-----------------------------------#
#1 Define log output destination as console
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
#### Flexibility to specify log output format , The following line specifies the specific format ###
#%c: Category of output log information , Usually the full name of the class
#%m: The message specified in the output code , Specific information of the generated log
#%n: Output a carriage return line feed ,Windows The platform is "/r/n",Unix The platform is "/n" Output log information line feed
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
#-----------------------------------#
#2 A new file is generated when the file size reaches the specified size
log4j.appender.file = org.apache.log4j.RollingFileAppender
# Log file output directory
log4j.appender.file.File=log/tibet.log
# Define maximum file size
log4j.appender.file.MaxFileSize=10mb
### Output log information ###
# The lowest level
log4j.appender.file.Threshold=ERROR
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
#-----------------------------------#
#3 druid
log4j.logger.druid.sql=INFO
log4j.logger.druid.sql.DataSource=info
log4j.logger.druid.sql.Connection=info
log4j.logger.druid.sql.Statement=info
log4j.logger.druid.sql.ResultSet=info
#4 mybatis Show SQL Statement part
log4j.logger.org.mybatis=DEBUG
#log4j.logger.cn.tibet.cas.dao=DEBUG
#log4j.logger.org.mybatis.common.jdbc.SimpleDataSource=DEBUG
#log4j.logger.org.mybatis.common.jdbc.ScriptRunner=DEBUG
#log4j.logger.org.mybatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
#log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
  1. mybatis-config.xml To configure
<!-- Set the log implementation Note that property settings are strictly case sensitive mybatis Of Commons Logging by :STDOUT_LOGGING-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!-- Set the log implementation Note that property settings are strictly case sensitive logj Realization way :LOG4J-->
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
  1. Test code
@Test
public void selectUser(){

SqlSessionFactory sqlSessionFactory = MybatisUtil.getSqlSessionFactory();
SqlSession session = sqlSessionFactory.openSession();
List<User> users = mapper.selectUser();
for (User user : users) {

System.out.println(user);
}
}

test result :

Commons Logging Implementation log

[org.apache.ibatis.logging.LogFactory]-Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
Class not found: org.jboss.vfs.VFS
JBoss 6 VFS API is not available in this environment.
Class not found: org.jboss.vfs.VirtualFile
VFS implementation org.apache.ibatis.io.JBoss6VFS is not valid in this environment.
Using VFS adapter org.apache.ibatis.io.DefaultVFS
Find JAR URL: file:/G:/IDEA%20Project/Mybatis/target/classes/com/hooi/pojo
Not a JAR: file:/G:/IDEA%20Project/Mybatis/target/classes/com/hooi/pojo
Reader entry: User.class
Listing file:/G:/IDEA%20Project/Mybatis/target/classes/com/hooi/pojo
Find JAR URL: file:/G:/IDEA%20Project/Mybatis/target/classes/com/hooi/pojo/User.class
Not a JAR: file:/G:/IDEA%20Project/Mybatis/target/classes/com/hooi/pojo/User.class
Reader entry: ���� 3 <
Checking to see if class com.hooi.pojo.User matches criteria [is assignable to Object]
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 183284570.
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@aecb35a]
==> Preparing: select * from user
==> Parameters:
<== Columns: id, name, pwd
<== Row: 1, HooiShieh, 123456
<== Row: 2, Zhang San , abcdef
<== Row: 3, Li Si , 987654
<== Total: 3
User{id=1, name='HooiShieh', password='123456'}
User{id=2, name=' Zhang San ', password='abcdef'}
User{id=3, name=' Li Si ', password='987654'}

log4j Implementation log

[org.apache.ibatis.logging.LogFactory]-Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
[org.apache.ibatis.logging.LogFactory]-Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
[org.apache.ibatis.io.VFS]-Class not found: org.jboss.vfs.VFS
[org.apache.ibatis.io.JBoss6VFS]-JBoss 6 VFS API is not available in this environment.
[org.apache.ibatis.io.VFS]-Class not found: org.jboss.vfs.VirtualFile
[org.apache.ibatis.io.VFS]-VFS implementation org.apache.ibatis.io.JBoss6VFS is not valid in this environment.
[org.apache.ibatis.io.VFS]-Using VFS adapter org.apache.ibatis.io.DefaultVFS
[org.apache.ibatis.io.DefaultVFS]-Find JAR URL: file:/G:/IDEA%20Project/Mybatis/target/classes/com/hooi/pojo
[org.apache.ibatis.io.DefaultVFS]-Not a JAR: file:/G:/IDEA%20Project/Mybatis/target/classes/com/hooi/pojo
[org.apache.ibatis.io.DefaultVFS]-Reader entry: User.class
[org.apache.ibatis.io.DefaultVFS]-Listing file:/G:/IDEA%20Project/Mybatis/target/classes/com/hooi/pojo
[org.apache.ibatis.io.DefaultVFS]-Find JAR URL: file:/G:/IDEA%20Project/Mybatis/target/classes/com/hooi/pojo/User.class
[org.apache.ibatis.io.DefaultVFS]-Not a JAR: file:/G:/IDEA%20Project/Mybatis/target/classes/com/hooi/pojo/User.class
[org.apache.ibatis.io.DefaultVFS]-Reader entry: ���� 3 <
[org.apache.ibatis.io.ResolverUtil]-Checking to see if class com.hooi.pojo.User matches criteria [is assignable to Object]
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Opening JDBC Connection
[org.apache.ibatis.datasource.pooled.PooledDataSource]-Created connection 183284570.
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@aecb35a]
[com.hooi.dao.UserMapper.selectUser]-==> Preparing: select * from user
[com.hooi.dao.UserMapper.selectUser]-==> Parameters:
[com.hooi.dao.UserMapper.selectUser]-<== Total: 3
User{id=1, name='HooiShieh', password='123456'}
User{id=2, name=' Zhang San ', password='abcdef'}
User{id=3, name=' Li Si ', password='987654'}

02 Mybatis Realize pagination display of query results

adopt limit Realize pagination display of query results

  1. mapper Interface
// adopt limit Realize pagination display of query results 
public abstract List<User> selectUserByLimit(Map<String,Integer> map);
  1. mapper The mapping file
 <select id="selectUserByLimit" parameterType="Map" resultMap="UserMap" >
select * from user limit #{startIndex},#{pageSize}
</select>
  1. Junit Test code
@Test
public void selectUserByLimit(){

SqlSessionFactory sqlSessionFactory = MybatisUtil.getSqlSessionFactory();
SqlSession session = sqlSessionFactory.openSession();
// Simulate getting data from users , In general , The user will only pass in the current page currentPage And page size pageSize
// The current position can be based on startIndex =(currentPage -1)*pageSize Calculation 
int currentPage = 2;
int pageSize = 2;
// Repackage the user's incoming data 
Map<String, Integer> map = new HashMap<>();
map.put("startIndex",(currentPage-1)*pageSize);
map.put("pageSize",pageSize);
UserMapper mapper = session.getMapper(UserMapper.class);
List<User> users = mapper.selectUserByLimit(map);
for (User user : users) {

System.out.println(user);
}
}
  1. test result

 Insert picture description here


adopt RowBounds Realize pagination display of query results

  1. mapper Interface
// adopt mybatis Provided rowBounds Realize pagination display of query results 
public abstract List<User> selectUserByRowBounds(Map<String,Integer> map);
  1. mapper The mapping file
<select id="selectUserByRowBounds" resultMap="UserMap" >
select * from user
</select>
  1. Junit Test code
@Test
public void selectUserByRowBounds(){

SqlSessionFactory sqlSessionFactory = MybatisUtil.getSqlSessionFactory();
SqlSession session = sqlSessionFactory.openSession();
// Simulate incoming data 
int currentPage = 1;
int pageSize = 3;
// Calculate the starting position 
int startIndex = (currentPage-1)*pageSize;
// Create a RowBounds object 
RowBounds rowBounds = new RowBounds(startIndex, pageSize);
// Be careful ; Use RowBounds Implement paging , You can't use it getMapper 了 
//selectList: Receive one List Need the parameter passed in 
//selectMap: Receive one Map
//selectOne : When receiving only one object 
List<User> users = session.selectList("com.hooi.dao.UserMapper.selectUserByRowBounds", null, rowBounds);
for (User user : users) {

System.out.println(user);
}
}
  1. test result

 Insert picture description here

limit and rowBounds difference

  • limit Is in SQL The layer implements paging , You need to get it first through reflection Mapper Interface , Re pass SqlSession get Mapper Implementation class of interface , Pass in parameters through the implementation class ( The starting position , Page size ), Realize paging display .
  • rowBounds Paging at the code level , There is no need to obtain Mapper Implementation class of interface , It needs to be constructed by parameters ( Pass in paging parameters ) establish RowBounds object , Re pass SqlSession Object call selectList,selectMap perhaps selectOne Method to implement paging . The parameters passed in are in turn corresponding to mapper The full domain name of the abstract method in the interface , A designated Objec object ( It’s usually null), as well as RowBounds object , Such as selectList(“com.hooi.dao.UserMapper.selectUserByRowBounds”,null,rowBounds).RowBounds The essence is to encapsulate limit.

03 Mybatis Optimized use of

Optimized use of transactions

public static SqlSession getSqlSession(){

// Turn on transaction auto commit ,openSession Constructor if the parameter is true, Then the transaction will automatically commit .
return sqlSessionFactory.openSession(true);
}

Optimized use of aliases

Automatically set alias

<typeAliases>
<!-- by pojo The class under the whole package automatically takes the alias -->
<package name="com.hooi.pojo"/>
</typeAliases>

Use the idea of annotation development

In the early Mybatis Is to use xml To configure , later , annotation The emergence of the began to replace some xml Configuration of .

CRUD Annotations :@insert() @delete() @update() @select()

Develop… Using annotations In essence An interface Development of

AnnotationDao.interface

package com.hooi.dao;
import com.hooi.pojo.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface AnnotationDao {

// Query all users 
@Select("select * from user")
public abstract List<User> getAllUsers();
// adopt id and name Query the user 
// Be careful : Passing in a single parameter can be omitted @Param Multiple parameters passed in must use @Param And separated by commas 
@Select("select * from user where id = #{id}")
public abstract User getUserById(@Param("id") int id );
// adopt id Delete user 
@Delete("delete from user where id = #{id}")
public abstract int delUserById(@Param("id") int id);
// Update user 
@Update("update user set name = #{name}, pwd = #{password} where id = #{id}")
public abstract int updateUser(User user);
// Add users 
@Insert("insert into user (id,name,pwd) values (#{id},#{name},#{password})")
public abstract int addUser(User user);
}

Using annotations for development does not require configuration mapper The mapping file , But it needs to be configured mybatis Configuration file for

<mappers>
<mapper class="com.hooi.dao.AnnotationDao"/>
</mappers>

Junit Test code :

package com.hooi.dao;
import com.hooi.pojo.User;
import com.hooi.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class AnnotationDaoTest {

@Test
public void getAllUsers(){

SqlSession session = MybatisUtil.getSqlSession();
AnnotationDao mapper = session.getMapper(AnnotationDao.class);
List<User> users = mapper.getAllUsers();
for (User user : users) {

System.out.println(user);
}
}
@Test
public void getUserById(){

SqlSession session = MybatisUtil.getSqlSession();
AnnotationDao mapper = session.getMapper(AnnotationDao.class);
User user = mapper.getUserById(3);
System.out.println(user);
}
@Test
public void delUserById(){

SqlSession session = MybatisUtil.getSqlSession();
AnnotationDao mapper = session.getMapper(AnnotationDao.class);
int updateRows = mapper.delUserById(6);
if (updateRows>0){

System.out.println("delete successfully");
}
}
@Test
public void updateUser(){

SqlSession session = MybatisUtil.getSqlSession();
AnnotationDao mapper = session.getMapper(AnnotationDao.class);
int updateRows = mapper.updateUser(new User(5,"lily","000000"));
if (updateRows>0){

System.out.println("update successfully");
}
}
@Test
public void addUser(){

SqlSession session = MybatisUtil.getSqlSession();
AnnotationDao mapper = session.getMapper(AnnotationDao.class);
int updateRows = mapper.addUser(new User(6,"Jackson","000000"));
if (updateRows>0){

System.out.println("add successfully");
}
}
}

test result :

  1. getAllUsers() test result

 Insert picture description here

  1. getUserById() test result

 Insert picture description here

  1. delUserById() test result

 Insert picture description here

  1. updateUser() test result

 Insert picture description here

  1. addUser() test result

 Insert picture description here


发表回复