编写log4j配置文件
在resources路径下
创建properties文件
命名为:log4j.properties
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
创建测试类
test/java目录下创建
xyz.zhouzhousag.test.MybatisTest
package xyz.zhouzhousag.test;
/**
* Description:
* <p>
* ClassName: MybatisTest
* date: 2021/3/1 11:25
*
* @author Yin.Liu
* @version 1.0
* @since JDK 1.8
*/
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 xyz.zhouzhousag.dao.IUserDAO;
import xyz.zhouzhousag.domain.User;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
*@ClassName MybatisTest
*@Description TODO
*@Author Yin.Liu8
*@Date 2021/3/1 11:25
*@Version 1.0
*/
public class MybatisTest {
/**
* 入门案例
* @param args
*/
public static void main(String[] args) throws Exception {
//1.读取配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建SqlSessionFactory工厂
SqlSessionFactoryBuilder sessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory build = sessionFactoryBuilder.build(in);
//3.使用工厂生产 SqlSession对象
SqlSession sqlSession = build.openSession();
//4.使用SqlSession创建DAO接口的代理对象
IUserDAO mapper = sqlSession.getMapper(IUserDAO.class);
//5.使用代理对象执行方法
List<User> all = mapper.findAll();
for (User user:all
) {
System.out.println(user.toString());
}
//6.释放资源
sqlSession.close();
in.close();
}
}
此时运行会报错:
It's likely that neither a Result Type nor a Result Map was specified.
我们还需要取mapper.xml中指定封装到哪里
修改IUserMapper.xml文件
<?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">
<!--namespace必须是dao接口的全限定类名-->
<mapper namespace="xyz.zhouzhousag.dao.IUserDAO">
<!--配置查询所有-->
<!--id 需和 IUserDAO接口的方法名称一致-->
<!--resultType 指明把 结果封装到哪里-->
<select id="findAll" resultType="xyz.zhouzhousag.domain.User">
select * from user
</select>
</mapper>
分析
使用了,
代理模式,
工厂模式,
构建者模式。