MyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架。
MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装。
MyBatis可以使用简单的XML或注解用于配置和原始映射,
将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录.
编写第一个基于mybaits的测试例子:
添加jar包
mybatis-3.1.1.jarmysql-connector-java-5.1.7-bin.jar
建库+表
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);
添加Mybatis的配置文件conf.xml(在src文件下)
<?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>
定义表所对应的实体类
public class User {
private int id;
private String name;
private int age;
//get,set方法
}
定义操作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.mybatis.userMapper">
<select id="selectUser" parameterType="int" resultType="com.mybatis.User">
select * from users where id=#{id}
</select>
</mapper>
在conf.xml文件中注册userMapper.xml文件
<mappers>
<mapper resource="com/mybatis/userMapper.xml"/>
</mappers>
编写测试代码:执行定义的select语句
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.mybatis.userMapper"+".selectUser";
//执行查询返回一个唯一user对象的sql
User user = session.selectOne(statement, 1);
System.out.println(user);
}
}
---
public static void main(String[] args) throws IOException {
String resource = "conf.xml";
InputStream is = Test.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session = factory.openSession();
String statement = "com.atguigu.day03_mybaits.test1.userMapper.getUser";
User user = session.selectOne(statement, 2);
System.out.println(user);
}
}