MyBatis
简介
什么是 MyBatis?
MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架。MyBatis 消除 了几乎所有的 JDBC 代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJOs(Plan Old Java Objects,普通的 Java 对象)映射成数据库中的记录。
Mybatis快速入门
1.添加jar包
mybatis:
mybatis-3.1.1.jar
oracle:
ojdbc6.jar(根据个人情况,不同数据库选择相应的包)
2.表
create table user_name (id number,name varchar2(200),age number);insert into user_name values(1,'ddd',23);insert into user_name values(2.'fff',24)
3.添加mybatis的配置文件config.xm
1 2 3 4 56 7 8 9 28 2910 11 26 2712 13 14 15 24 2516 17 18 19 20 21 22 23
4.定义表所对应的实体类
package cn.zr.maybatis;public class User { private String id; private String userName; private String passWord; public User() { super(); // TODO Auto-generated constructor stub } public User(String id, String userName, String passWord) { super(); this.id = id; this.userName = userName; this.passWord = passWord; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassWord() { return passWord; } public void setPassWord(String passWord) { this.passWord = passWord; } @Override public String toString() { return "User [id=" + id + ", userName=" + userName + ", passWord=" + passWord + "]"; } }
5.定义操作user_name表的sql映射文件userMapper.xml
6.在config.xml文件中注册userMapper.xml文件
7.编写测试代码,执行定义的select语句
public class Test { public static void main(String[] args) throws IOException { String resource = "config.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); session.commit(); session.close(); }}