入门demo官方参考文档:https://mybatis.org/mybatis-3/zh/getting-started.html
步骤:
use `mybatis`;
create table `user`(
`id` int(20) not null primary key ,
`name`varchar(30) default null,
`password` varchar(30) default null
)engine = innodb charset=utf8
insert into `user`(`id`,`name`,`pw`)values
(1,'关羽','123'),
(2,'张飞','456'),
(3,'刘备','123456')
新建maven文件:mybatis
在mybatis文件下:新建mybatis_demo_01 子模块
导入maven依赖:
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.10version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.28version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
dependencies>
文件名:mybatis-config.xml
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value=""/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/lyf/dao/mapper/UserMapper.xml">mapper>
mappers>
configuration>
文件名:User.class
public class User {
private int id;
private String username;
private String password;
public User(){}
public User(int id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
// get()...
// set()...
}
文件名:UserMapper.xml
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lyf.dao.UserDao">
<select id="getUserList" resultType="com.lyf.entity.User" >
select * from mybatis.user
select>
mapper>
文件名:log4j.properties
log4j.rootCategory=INFO, stdout , R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[QC] %p [%t] %C.%M(%L) | %m%n
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=./logs/jy.log
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d-[TS] %p %t %c - %m%n
log4j.logger.com.neusoft=DEBUG
log4j.logger.com.opensymphony.oscache=ERROR
log4j.logger.net.sf.navigator=ERROR
log4j.logger.org.apache.commons=ERROR
log4j.logger.org.apache.struts=WARN
log4j.logger.org.displaytag=ERROR
log4j.logger.org.springframework=DEBUG
log4j.logger.com.ibatis.db=WARN
log4j.logger.org.apache.velocity=FATAL
log4j.logger.com.canoo.webtest=WARN
log4j.logger.org.hibernate.ps.PreparedStatementCache=WARN
log4j.logger.org.hibernate=DEBUG
log4j.logger.org.logicalcobwebs=WARN
#将等级为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/jyy.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
文件名:UserMapperTest.class
注意:
测试使用初始化方法
加载文件方式;
后续将初始化方法封装成一个工具类:MybatisUtils.class
, 直接获取sqlSession
public class UserMapperTest {
// 配置 SqlSessionFactory 工厂
private static SqlSessionFactory sqlSessionFactory;
/**
* 加载配置文件
*/
@BeforeClass
public static void init(){
try{
// 1. Resources工具类 加载 mybatis-config.xml配置文件
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
// 2.SqlSessionFactoryBuilder 建造类 生成 SqlSessionFactory 工厂对象
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 测试方法
*/
@Test
public void testSelectAll(){
// 3. SqlSessionFactory 工厂 获取一个SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
try{
// 4.SqlSession的selectList方法 查找到 UserMapper中 id= "selectALL" 的方法,执行SQL查询
// 5.获得查询结果集Result后,根据resultType的配置将结果映射为User类型的集合
List<User> selectAll = sqlSession.selectList("selectAll");
// 6. 输出最后的查询结果UserList,
System.out.println(selectAll);
// 遍历输出
for (User user : selectAll) {
System.out.println(user);
}
}finally {
// 7.关闭sqlSession
sqlSession.close();
}
}
}
控制台输出: