1.添加jar包
【mybatis】
mybatis-3.1.1.jar
【MYSQL 驱动包】
mysql-connector-java-5.1.7-bin.jar
2.建库+建表
create database mybatis;
use mybatis;
CREATE TABLE users(id INT PRIMARY KEY AUTO_INCREMENT, NAME
VARCHAR(20), age INT);
INSERT INTO users(NAME, age) VALUES('Tom', 12);
INSERT INTO users(NAME, age) VALUES('Jack', 11);
3.添加Mybatis的配置文件conf.xml
<?xml version="1.0" encoding="UTF-8"?>
<!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.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
</configuration>
4.定义表对应的实体类
public class User {
private int id;
private String name;
private int age;
//get,set 方法
}
5.定义操作users表的sql映射文件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">
<mapper namespace=" com.atguigu.mybatis_test.test1.userMapper">
<select id="getUser" parameterType="int"
resultType="com.atguigu.mybatis_test.test1.User">
select * from users where id=#{id}
</select>
</mapper>
6.在conf.xml文件中注册userMapper.xml文件
<mappers>
<mapper resource="com/atguigu/mybatis_test/test1/userMapper.xml"/>
</mappers>
7.编写测试代码:执行定义的语句
public class Test {
public static void main(String[] args) throws IOException {
String resource = "conf.xml";
//加载 mybatis 的配置文件(它也加载关联的映射文件)
Reader reader = Resources.getResourceAsReader(resource);
//构建 sqlSession 的工厂
SqlSessionFactory sessionFactory = new
SqlSessionFactoryBuilder().build(reader);
//创建能执行映射文件中 sql 的 sqlSession
SqlSession session = sessionFactory.openSession();
//映射 sql 的标识字符串
String statement = "com.atguigu.mybatis.bean.userMapper"+".selectUser";
//执行查询返回一个唯一 user 对象的 sql
User user = session.selectOne(statement, 1);
System.out.println(user);
}
}