6.1 log4j使用
配套视频:【编程不良人】Mybatis 从入门到精通_哔哩哔哩_bilibili
相关jar包:
<dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.14.1</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.14.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.32</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.25</version> </dependency>
视频中log4j.properties
log4j.rootLogger = ERROR,stdout log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.conversionPattern = %d{yyyy-MM-dd} %t %c [%p] %m%n log4j.dao = DEBUG
StudentDAOTest2.java运行findByIdTest结果
(1)ERROR,stdout
Student{id=1, name='张三', age=15}
(2)DEBUG,stdout
2022-04-09 main org.apache.ibatis.logging.LogFactory [DEBUG] Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter. 2022-04-09 main org.apache.ibatis.datasource.pooled.PooledDataSource [DEBUG] PooledDataSource forcefully closed/removed all connections. 2022-04-09 main org.apache.ibatis.datasource.pooled.PooledDataSource [DEBUG] PooledDataSource forcefully closed/removed all connections. 2022-04-09 main org.apache.ibatis.datasource.pooled.PooledDataSource [DEBUG] PooledDataSource forcefully closed/removed all connections. 2022-04-09 main org.apache.ibatis.datasource.pooled.PooledDataSource [DEBUG] PooledDataSource forcefully closed/removed all connections. 2022-04-09 main org.apache.ibatis.transaction.jdbc.JdbcTransaction [DEBUG] Opening JDBC Connection 2022-04-09 main org.apache.ibatis.datasource.pooled.PooledDataSource [DEBUG] Created connection 521960438. 2022-04-09 main org.apache.ibatis.transaction.jdbc.JdbcTransaction [DEBUG] Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1f1c7bf6] 2022-04-09 main dao.StudentDAO.findById [DEBUG] ==> Preparing: select id,name,age from student where id=? 2022-04-09 main dao.StudentDAO.findById [DEBUG] ==> Parameters: 1(Integer) 2022-04-09 main dao.StudentDAO.findById [DEBUG] <== Total: 1 Student{id=1, name='张三', age=15} 2022-04-09 main org.apache.ibatis.transaction.jdbc.JdbcTransaction [DEBUG] Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1f1c7bf6] 2022-04-09 main org.apache.ibatis.transaction.jdbc.JdbcTransaction [DEBUG] Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1f1c7bf6] 2022-04-09 main org.apache.ibatis.datasource.pooled.PooledDataSource [DEBUG] Returned connection 521960438 to pool.
(待完善)若进行如下细节设置,测试还存在问题:
### 设置### log4j.rootLogger = debug,stdout,D,E ### 输出信息到控制抬 ### log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n ### 输出DEBUG级别以上的日志到=D://logs/debug.log ### log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File = D://Software_Development/IDEA_code/logs/debug.log //日志输出路径 可更改 log4j.appender.D.Append = true log4j.appender.D.Threshold = DEBUG log4j.appender.D.layout = org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n ### 输出ERROR级别以上的日志到=E://logs/error.log ### log4j.appender.E = org.apache.log4j.DailyRollingFileAppender log4j.appender.E.File =D://Software_Development/IDEA_code/logs/error.log log4j.appender.E.Append = true log4j.appender.E.Threshold = ERROR log4j.appender.E.layout = org.apache.log4j.PatternLayout log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
测试代码:
package log4j; import org.apache.log4j.Logger; /** * @ClassName TestLog4j * @Description TODO * @Author Jiangnan Cui * @Date 2022/4/9 22:00 * @Version 1.0 */ public class TestLog4j { private static final Logger logger = Logger.getLogger(Logger.class); public static void main(String[] args) { //记录info级别的信息 logger.info("这是info级别的信息"); //记录debug级别的信息 logger.debug("这是debug级别的信息"); //记录error级别的信息 logger.error("这是error级别的信息"); } }
运行结果:
log4j:ERROR setFile(null,true) call failed. java.io.FileNotFoundException: D:\Software_Development\IDEA_code\logs\debug.log \ÈÕÖ¾Êä³ö·¾¶ ¿É¸ü¸Ä (系统找不到指定的路径。) at java.io.FileOutputStream.open0(Native Method) at java.io.FileOutputStream.open(FileOutputStream.java:270) at java.io.FileOutputStream.<init>(FileOutputStream.java:213) at java.io.FileOutputStream.<init>(FileOutputStream.java:133) at org.apache.log4j.FileAppender.setFile(FileAppender.java:294) at org.apache.log4j.FileAppender.activateOptions(FileAppender.java:165) at org.apache.log4j.DailyRollingFileAppender.activateOptions(DailyRollingFileAppender.java:223) at org.apache.log4j.config.PropertySetter.activate(PropertySetter.java:307) at org.apache.log4j.config.PropertySetter.setProperties(PropertySetter.java:172) at org.apache.log4j.config.PropertySetter.setProperties(PropertySetter.java:104) at org.apache.log4j.PropertyConfigurator.parseAppender(PropertyConfigurator.java:842) at org.apache.log4j.PropertyConfigurator.parseCategory(PropertyConfigurator.java:768) at org.apache.log4j.PropertyConfigurator.configureRootCategory(PropertyConfigurator.java:648) at org.apache.log4j.PropertyConfigurator.doConfigure(PropertyConfigurator.java:514) at org.apache.log4j.PropertyConfigurator.doConfigure(PropertyConfigurator.java:580) at org.apache.log4j.helpers.OptionConverter.selectAndConfigure(OptionConverter.java:526) at org.apache.log4j.LogManager.<clinit>(LogManager.java:127) at org.apache.log4j.Logger.getLogger(Logger.java:117) at log4j.TestLog4j.<clinit>(TestLog4j.java:13) log4j:ERROR Either File or DatePattern options are not set for appender [D]. [INFO ] 2022-04-09 23:05:48,318 method:log4j.TestLog4j.main(TestLog4j.java:17) 这是info级别的信息 [DEBUG] 2022-04-09 23:05:48,320 method:log4j.TestLog4j.main(TestLog4j.java:19) 这是debug级别的信息 [ERROR] 2022-04-09 23:05:48,320 method:log4j.TestLog4j.main(TestLog4j.java:21) 这是error级别的信息
参考链接:
-
IDEA中log4j.properties配置文件详解 - 百度文库
-
idea中log4j的简单使用 - 种瓜得豆。 - 博客园
6.2 排序(order by)
sql语句:
-- 格式:select 字段1,字段2,... from 表名 order by 字段名 asc/desc -- 其中,asc表示升序(默认的排序方式,可省略不写),desc表示降序 SELECT id,name,age FROM student ORDER BY name
查询结果:
6.3 分页查询(limit)
配套视频:【编程不良人】Mybatis 从入门到精通_哔哩哔哩_bilibili
分页前一般先排序,这里以age进行降序排列,每条显示5条数据为例,进行说明
-- 降序排列 SELECT id,NAME,age FROM student ORDER BY age DESC
-- 语法:limit 起始值 页面的大小 -- 格式:select 字段1,字段2,... from 表名 order by 字段名 limit (n-1)*pageSize,pageSize -- 其中,pageSize表示页面大小,(n-1)*pageSize表示起始值,n表示当前页,总页数=数据总数/页面大小 -- 以每页显示5条数据为例 -- 查询第1页 (1-1)*5=0,5 第1页从0开始,范围为0-4,对应第1到第5条数据 SELECT id,name,age FROM student ORDER BY age DESC LIMIT 0,5
-- 查询第2页 (2-1)*5=5,5 第2页从5开始,范围为5-9,对应第6到第10条数据 SELECT id,NAME,age FROM student ORDER BY age DESC LIMIT 5,5
-- 查询第3页 (3-1)*5=10,5 第3页从10开始,范围为10-14,对应第11到第15条数据 SELECT id,NAME,age FROM student ORDER BY age DESC LIMIT 10,5
StudentDAO.java
/** * @MethodName selectByPage * @Description * @param: pageNow 当前页码 * @param: pageSize 每页显示信息条数 * @return: java.util.List<entity.Student> * @Author Jiangnan Cui * @Date 2022/4/10 16:16 */ List<Student> selectByPage(Map<String,Integer> map);
StudentDAOMapper.xml
<!--分页查询--> <select id="selectByPage" parameterType="map" resultType="entity.Student"> select id,name,age from student order by age desc limit #{pageStart},#{pageSize} </select>
测试
/** * @MethodName selectByPage * @Description 分页查询 * @Author Jiangnan Cui * @Date 2022/4/10 16:23 */ @Test public void selectByPage(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); StudentDAO studentDAO = sqlSession.getMapper(StudentDAO.class); HashMap<String,Integer> map = new HashMap<>(); map.put("pageStart",0);//第1页从0开始,范围为0-4,对应第1到第5条数据 map.put("pageSize",5); List<Student> students1 = studentDAO.selectByPage(map); System.out.println("---------------第1页----------------"); students1.forEach(student -> System.out.println(student)); map.put("pageStart",5);//第2页从5开始,范围为5-9,对应第6到第10条数据 map.put("pageSize",5); List<Student> students2 = studentDAO.selectByPage(map); System.out.println("---------------第2页----------------"); students2.forEach(student -> System.out.println(student)); map.put("pageStart",10);//第3页从10开始,范围为10-14,对应第11到第15条数据 map.put("pageSize",5); List<Student> students3 = studentDAO.selectByPage(map); System.out.println("---------------第3页----------------"); students3.forEach(student -> System.out.println(student)); sqlSession.close(); }
输出结果:
---------------第1页---------------- Student{id=13, name='慢羊羊', age=70} Student{id=3, name='光头强', age=37} Student{id=5, name='小猪猪', age=28} Student{id=6, name='猪猪侠', age=25} Student{id=9, name='熊大', age=20} ---------------第2页---------------- Student{id=7, name='猪小呆', age=19} Student{id=2, name='小呆呆', age=18} Student{id=10, name='熊二', age=16} Student{id=1, name='张三', age=15} Student{id=12, name='暖羊羊', age=14} ---------------第3页---------------- Student{id=11, name='沸羊羊', age=12} Student{id=4, name='喜洋洋', age=6} Student{id=8, name='皮卡丘', age=5}
参考链接:
-
Mybatis--->limit分页查询 - Spring_Xian - 博客园
-
Mybatis中实现limit分页查询_努力学习搞钱的博客-CSDN博客_mybatis 查询limit
6.4 模糊查询(like)
以在name中模糊查询“猪”为例,sql语句:
-- 格式:select 字段1,字段2,... from 表名 where 字段名 like ’%要查询的模糊词%‘ -- %模糊词: 表示前模糊 -- 模糊词%: 表示后模糊 -- %模糊词%:表示中间模糊 SELECT id,name,age FROM student WHERE name LIKE '%猪%'
数据库中查询结果:
StudentDAO.java
//模糊查询 List<Student> selectByLike(String keyWords);
StudentDAOMapper.xml
<!--模糊查询--> <select id="selectByLike" parameterType="String" resultType="entity.Student"> select id,name,age from student where name like "%"#{keyWords}"%"; </select>
测试
/** * @MethodName selectByLikeTest * @Description 模糊查询 * @Author Jiangnan Cui * @Date 2022/4/10 12:21 */ @Test public void selectByLikeTest(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); StudentDAO studentDAO = sqlSession.getMapper(StudentDAO.class); List<Student> students = studentDAO.selectByLike("小"); for (Student student : students) { System.out.println(student); } }
输出结果:
Student{id=5, name='小猪猪', age=28} Student{id=6, name='猪猪侠', age=25} Student{id=7, name='猪小呆', age=19}
6.5 实体类别名设置
实体类起别名对应代码:
<!--给实体类起别名,方便在XxxDAOMapeer.xml文件中进行简写--> <typeAliases> <!--type为要起别名的类对应的全限定名,alias为起的别名--> <typeAlias type="entity.Student" alias="Student"/> </typeAliases>
6.6 引入properties配置文件
jdbc.properties
driver = com.mysql.cj.jdbc.Driver url = jdbc:mysql://localhost:3306/mybatis username = root password = 123456
mybatis-config.xml
<!--配置mybatis环境--> <configuration> <!--引入jdbc.properties配置文件--> <properties resource="jdbc.properties"/> <!-- 配置连接数据库使用的相关参数,default为默认使用的环境 其中,development表示测试环境,可简写为dev produc表示生产环境,可简写为prod --> <environments default="development"> <!--测试环境--> <environment id="development"> <!--事务管理类型:指定事务管理的方式 JDBC--> <transactionManager type="JDBC"/> <!--数据库连接相关配置,动态获取config.properties文件里的内容--> <!--数据源类型:POOLED 表示支持JDBC数据源连接池 UNPOOLED 表示不支持数据源连接池 JNDI 表示支持外部数据源连接池 --> <dataSource type="POOLED"> <!--此处使用的是MySQL数据库,使用Oracle数据库时需要修改,仔细检查各项参数是否正确--> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> </configuration>