1、在mysql中执行下面的sql
CREATE DATABASE mybatisdb;
USE mybatisdb;
CREATE TABLE USER(id INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(100),addr VARCHAR(100),age INT);
INSERT INTO USER VALUES(NULL,'张三','北京',28);
INSERT INTO USER VALUES(NULL,'李四','上海',30);
INSERT INTO USER VALUES(NULL,'王五','广州',19);
2、创建一个普通的java工程,引入jar包
在项目上右键,创建一个文件夹起名为lib
把jar包复制粘贴到项目目录下
右键BuildPath ->Add to Build Path
3、创建pojo包,在包下创建User类
User 类的代码如下
package pojo;
/**
* 这个类用来和User表做映射关系 要求:属性名必须和表字段名保持一致
*/
public class User {
// id
private int id;
// 用户名
private String name;
// 地址
private String addr;
// 年龄
private int age;
// getter setter
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", addr=" + addr + ", age=" + age + "]";
}
}
4在pojo包下,创建UserMapper.xml
/mybatis1/src/pojo/UserMapper.xml
UserMapper.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命名空间:是该文件的唯一标识 (ns是namespace缩写) -->
<mapper namespace="userns">
<!--select标签,用来完成一个查询的sql,
id是sql的唯一标识
resultType是值结果集要封装给哪个实体,它的
值是类的全路径(包名+类名)
-->
<select id="all" resultType="pojo.User">
select * from user
</select>
</mapper>
5在src目录下创建sqlMapConfig.xml
/mybatis1/src/sqlMapConfig.xml
sqlMapConfig.xml代码如下(<mappers></mappers>是mapper仓库)
<?xml version="1.0" encoding="UTF-8"?>
<!--xml约束信息-->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--配置开发环境 default用来设置默认的开发环境 可以包含很多的environment -->
<environments default="test">
<!-- 测试环境 -->
<environment id="test">
<!--事务管理器:mybatis的事务交给jdbc来管理 -->
<transactionManager type="jdbc"></transactionManager>
<!-- 连接池:配置数据源(连接池),池化的 -->
<dataSource type="pooled">
<!-- 数据库的驱动名字 -->
<property name="driver" value="com.mysql.jdbc.Driver" />
<!-- 数据库的url地址 -->
<property name="url" value="jdbc:mysql:///mybatisdb" />
<!-- 数据库的用户名 -->
<property name="username" value="root" />
<!-- 数据库的密码 -->
<property name="password" value="g" />
</dataSource>
</environment>
<!-- 开发环境 <environment id=""> </environment> -->
</environments>
<!-- 引入映射文件 -->
<mappers>
<!-- 引入UserMapper.xml resource指定文件的位置,右键-Copy Qualified Name -->
<mapper resource="pojo/UserMapper.xml" />
</mappers>
</configuration>
6在src下创建空白文件,名称为log4j.properties
在文件内输入如下内容后保存
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
7在src下创建test包,在包下创建TestUser测试类
TestUser
package test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
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 org.junit.Test;
import pojo.User;
/*
* 测试User是否能成功查询
*/
public class TestUser {
@Test
public void testUserQuery() throws IOException{
//1.创建会话工厂
InputStream in=Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory ssf=new SqlSessionFactoryBuilder().build(in);
//2.创建Sqlsession,执行sql
SqlSession session = ssf.openSession();
//参数为定位sql的位置namespace值.id值
List<User> list = session.selectList("userns.all");
//3.处理结果
for (User user : list) {
System.out.println(user);
}
//4.释放资源
session.close();
}
}
8双击选中testUserQuery方法,右键RunAs ->JUnit Test
进度条变绿,控制台正常输出数据库表内容表示成功
控制台内容如下
DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection 119981396.
DEBUG [main] - ooo Using Connection [com.mysql.jdbc.JDBC4Connection@726c554]
DEBUG [main] - ==> Preparing: select * from user
DEBUG [main] - ==> Parameters:
User [id=1, name=张三, addr=北京, age=28]
User [id=2, name=李四, addr=上海, age=30]
User [id=3, name=王五, addr=广州, age=19]
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@726c554]
DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@726c554]
DEBUG [main] - Returned connection 119981396 to pool.
可发现底层其实是jdbc和连接池操作,最后一句话是归还连接池