Mybatis培訓教程
1.?Mybatis介紹
MyBatis是支持普通SQL查詢,存儲過程和高級映射的優(yōu)秀持久層框架。MyBatis消除了幾乎所有的JDBC代碼和參數的手工設置以及對結果集的檢索封裝。MyBatis可以使用簡單的XML或注解用于配置和原始映射,將接口和Java的POJO(Plain Old Java Objects,普通的Java對象)映射成數據庫中的記錄.
JDBC-àdbutils-àMyBatis-àHibernate
1.?mybatis快速入門
編寫第一個基于mybaits的測試例子:
2.1. 添加jar包
【mybatis】 mybatis-3.1.1.jar 【MYSQL驅動包】 |
2.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); |
2.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> |
2.4.?定義表所對應的實體類
public class User { private int id; private String name; private int age; ????//get,set方法 } |
2.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> |
2.6.?在conf.xml文件中注冊userMapper.xml文件
<mappers> <mapper resource="com/atguigu/mybatis_test/test1/userMapper.xml"/> </mappers> |
?
2.7.?編寫測試代碼:執(zhí)行定義的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); //創(chuàng)建能執(zhí)行映射文件中sql的sqlSession SqlSession session = sessionFactory.openSession(); //映射sql的標識字符串 String statement = "com.atguigu.mybatis.bean.userMapper"+".selectUser"; //執(zhí)行查詢返回一個唯一user對象的sql User user = session.selectOne(statement, 1); System.out.println(user); } } |
本教程由尚硅谷教育大數據研究院出品,如需轉載請注明來源,歡迎大家關注尚硅谷公眾號(atguigu)了解更多。