1.ORM模型简介:
2.传统jdbc的缺陷
3.mybatis的概述:
4.mybatis的说明文档官网http://www.mybatis.org/mybatis-3/zh/getting-started.html;
要使用 MyBatis, 只需将 文件置于 classpath 中即可。
如果使用 Maven 来构建项目,则需将下面的 dependency 代码置于 pom.xml 文件中和测试的junit包:
4.0.0 com.xiaoqiang,mybatis mybatisDemo 1.0-SNAPSHOT org.mybatis mybatis 3.4.6 mysql mysql-connector-java 5.1.6 junit junit 4.12 test
创建数据库表中的映射实体类:
package com.xiaoqiang.entity;public class User { private int id; private String name; private String className; private String score; @Override public String toString() { return "User{ " + "id=" + id + ", name='" + name + '\'' + ", className='" + className + '\'' + ", score='" + score + '\'' + '}'; } 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 String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getScore() { return score; } public void setScore(String score) { this.score = score; }}
设置mybatis.xml中的配置
创建mapper.xml映射关联
insert into user (id,name,className,score) values (#{nane},#{className},#{score});
通过Test来测试下插入跟查询
import com.xiaoqiang.entity.User;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.IOException;import java.io.InputStream;import java.util.List;public class Test { @org.junit.Test public void ceshi() throws IOException { String resource="mybatis.xml"; InputStream inputStream= Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession=sqlSessionFactory.openSession(); User user=new User(); user.setName("黄豪强"); user.setClassName("软件工程2班"); user.setScore("100"); user.setId(1); int success=sqlSession.insert("insertUser",user); sqlSession.commit(); System.out.println(success); /* Listlist=sqlSession.selectList("selectBlog"); for(User user:list) { System.out.println(user); }*/ sqlSession.close(); }}
mybatis整个流程图,主要操作部分为图中蓝色部分,SqlSessionFactory会话工厂只需执行一次:
mybatis整个架构流程: