1.Mybatis介绍
MyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装。MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录.
JDBC->dbutils->MyBatis->Hibernate
2.快速入门
步骤一:添加相应的jar包
【mybatis】
mybatis-3.1.1.jar
【mysql】
mysql-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的配置文件mybatis-config.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="1234" /> </dataSource> </environment> </environments> </configuration>
步骤四:定义表所对应的实体类
package com.lhs.model; public class User { private int id; private String name; private int age; 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 int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", age=" + age + "]"; } }
步骤五:定义操作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.lhs.model.userMapper">
<select id="getUser" parameterType="int"
resultType="com.lhs.model.User">
select * from users where id=#{id}
</select>
</mapper>
注:上面userMapper.xml文件里的红色部分为相当于标识改文件的唯一id,一般写法为改文件所在包名加上其名称
步骤六:在conf.xml文件中注册userMapper.xml文件
<mappers> <mapper resource="com/lhs/model/userMapper.xml"/> </mappers>
步骤七:编写测试代码,执行定义的select语句
@Test public void test1() { //加载mybatis的配置文件 InputStream is = Test.class.getClassLoader().getResourceAsStream("mybatis-config.xml"); //构建sqlSession的工厂 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is); //创建能执行映射文件中sql的sqlSession SqlSession session = factory.openSession(); //映射sql的标识字符串 String statement = "com.lhs.model.userMapper.getUser"; //执行查询返回一个唯一user对象的sql User user = session.selectOne(statement, 2); System.out.println(user); }
打印结果为:
成功!