一、MyBatis简介
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java POJO(Plain Old Java Objects,普通的 Java 对象)为数据库中的记录。
二、MyBatis Hello World实例
1、创建数据库和表:
CREATE DATABASE mybatis_test;USE mybatis_test;CREATE TABLE `user` (`id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(20) DEFAULT NULL,`age` int(11) DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
2、创建实体类:
public class User {private int id;private String name;private int age;//省略getter/setter方法}
3、创建Mapper接口:
public interface UserMapper {User selectUserById(int id);}
4、创建MyBatis配置文件:
<?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_test"/><property name="username" value="root"/><property name="password" value="root"/></dataSource></environment></environments><mappers><mapper resource="mapper/UserMapper.xml"/></mappers></configuration>
5、创建Mapper映射文件:
<?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.test.UserMapper"><select id="selectUserById" resultType="com.test.User">SELECT * FROM user WHERE id = #{id}</select></mapper>
6、编写测试类:
public class MyBatisTest {public static void main(String[] args) throws IOException {String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession session = sqlSessionFactory.openSession();try {UserMapper mapper = session.getMapper(UserMapper.class);User user = mapper.selectUserById(1);System.out.println(user.getName());} finally {session.close();}}}
三、MyBatis Hello World结果
编写完上面的代码并运行后,会在控制台上输出“张三”,表示我们的MyBatis Hello World实例已经成功实现。